1
我正在制作一个java程序,在列表框中产生一个接受器,它将显示项目的数量,项目名称和项目的价格。我需要填充字符串,以便名称在中间粗略显示,物品数量和成本都在乙方。你可以找到字符串的像素,然后我可以计算出实现所需格式所需的空间数量。由于Swing JList字体宽度
我正在制作一个java程序,在列表框中产生一个接受器,它将显示项目的数量,项目名称和项目的价格。我需要填充字符串,以便名称在中间粗略显示,物品数量和成本都在乙方。你可以找到字符串的像素,然后我可以计算出实现所需格式所需的空间数量。由于Swing JList字体宽度
这是你如何得到一个字符串的宽度:
Graphics2D g2d = (Graphics2D)g;
FontMetrics fontMetrics = g2d.getFontMetrics();
int width = fontMetrics.stringWidth("aString");
int height = fontMetrics.getHeight();
...
但是,因为我读了你的问题,我再次因子评分,为什么不使用JList的ListCellRenderer?它的工作原理,只要你想:
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);
}
看到我更新的代码,我认为这是你真正想要的! :) – dacwe 2010-11-24 15:39:24