Java Swing JList字体宽度
我正在制作一个java程序,在一个列表框中生成一个recept,它将显示项目的数量、项目名称和项目的价格。我需要垫线,使名称是粗鲁的中间,项目的数量和成本在以太方面。你能找到以像素为单位的字符串吗?然后我可以计算出实现所需格式所需的空间数。谢谢这是获取字符串宽度的方法:Java Swing JList字体宽度,java,swing,jlist,Java,Swing,Jlist,我正在制作一个java程序,在一个列表框中生成一个recept,它将显示项目的数量、项目名称和项目的价格。我需要垫线,使名称是粗鲁的中间,项目的数量和成本在以太方面。你能找到以像素为单位的字符串吗?然后我可以计算出实现所需格式所需的空间数。谢谢这是获取字符串宽度的方法: Graphics2D g2d = (Graphics2D)g; FontMetrics fontMetrics = g2d.getFontMetrics(); int width = fontMetrics.stringWid
Graphics2D g2d = (Graphics2D)g;
FontMetrics fontMetrics = g2d.getFontMetrics();
int width = fontMetrics.stringWidth("aString");
int height = fontMetrics.getHeight();
...
但是,当我再次阅读你的问题时,我想,为什么不使用in?它可以根据您的需要工作:
下面是它的代码:
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);
}
看到我更新的代码,我想这才是你真正想要的!:)