2010-11-24 85 views
1

我正在製作一個java程序,在列表框中產生一個接受器,它將顯示項目的數量,項目名稱和項目的價格。我需要填充字符串,以便名稱在中間粗略顯示,物品數量和成本都在乙方。你可以找到字符串的像素,然後我可以計算出實現所需格式所需的空間數量。由於Swing JList字體寬度

+0

看到我更新的代碼,我認爲這是你真正想要的! :) – dacwe 2010-11-24 15:39:24

回答

2

這是你如何得到一個字符串的寬度:

Graphics2D g2d = (Graphics2D)g; 
FontMetrics fontMetrics = g2d.getFontMetrics(); 

int width = fontMetrics.stringWidth("aString"); 
int height = fontMetrics.getHeight(); 

... 

但是,因爲我讀了你的問題,我再次因子評分,爲什麼不使用JListListCellRenderer?它的工作原理,只要你想:

http://img189.imageshack.us/img189/7509/jlistexample.jpg

這裏是它的代碼:

public static void main(String... args) { 

    JFrame frame = new JFrame("Test"); 

    JList list = new JList(new String[] { 
      "Hello", "World!", "as", "we", "know", "it" }); 

    list.setCellRenderer(new ListCellRenderer() { 

     @Override 
     public Component getListCellRendererComponent(
       JList list, 
       Object value, 
       int index, 
       boolean isSelected, 
       boolean cellHasFocus) { 

      JPanel panel = new JPanel(new GridBagLayout()); 

      if (isSelected) 
       panel.setBackground(Color.LIGHT_GRAY); 

      panel.setBorder(BorderFactory.createMatteBorder(
        index == 0 ? 1 : 0, 1, 1, 1, Color.BLACK)); 

      GridBagConstraints gbc = new GridBagConstraints(); 

      gbc.anchor = GridBagConstraints.EAST; 
      gbc.fill = GridBagConstraints.HORIZONTAL; 
      gbc.insets = new Insets(4,4,4,4); 

      // index 
      gbc.weightx = 0; 
      panel.add(new JLabel("" + index), gbc); 

      // "name" 
      gbc.weightx = 1; 
      panel.add(new JLabel("" + value), gbc); 

      // cost 
      gbc.weightx = 0; 
      String cost = String.format("$%.2f", Math.random() * 100); 
      panel.add(new JLabel(cost), gbc); 


      return panel; 
     } 
    }); 

    frame.add(list); 

    frame.setSize(400, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
}