Swing JList字体宽度

时间:2010-11-24 15:03:41

标签: java swing jlist

我正在制作一个java程序,在列表框中生成一个接收器,它将显示项目数,项目名称和项目价格。我需要填充字符串,以便名称在中间,并且项目数和成本在以太侧。你能找到字符串的像素,然后我可以计算出实现所需格式所需的空格数。感谢

1 个答案:

答案 0 :(得分:2)

这是获取字符串宽度的方法:

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

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

...

但是,当我再次阅读你的问题时,为什么不使用ListCellRenderer中的JList?它可以按你的意愿工作:

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);
}