【发布时间】:2010-12-07 17:14:14
【问题描述】:
我正在制作一个 java 程序,在列表框中生成一个收据,它将显示商品数量、商品名称和商品价格。我需要填充字符串,以便名称位于中间,并且项目数量和成本位于以太一侧。你能找到以像素为单位的字符串,然后我可以计算达到所需格式所需的空格数。谢谢
【问题讨论】:
-
看我更新的代码,我想这就是你真正想要的! :)
我正在制作一个 java 程序,在列表框中生成一个收据,它将显示商品数量、商品名称和商品价格。我需要填充字符串,以便名称位于中间,并且项目数量和成本位于以太一侧。你能找到以像素为单位的字符串,然后我可以计算达到所需格式所需的空格数。谢谢
【问题讨论】:
这是获取字符串宽度的方法:
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);
}
【讨论】: