How to calculate the font's width?

后端 未结 6 1542
眼角桃花
眼角桃花 2020-12-15 09:52

I am using java to draw some text, but it is hard for me to calculate the string\'s width. for example: zheng中国... How long will this string occupy?

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 10:22

    here is a simple app that can show you how to use FontMetrics when testing the width of a String:

    import java.awt.*;
    import java.awt.event.*;
    
    import javax.swing.*;
    
    public class GUITest {
        JFrame frame;
        public static void main(String[] args){
            new GUITest();
        }
        public GUITest() {
            frame = new JFrame("test");
            frame.setSize(300,300);
            addStuffToFrame();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    frame.setVisible(true);
                }
            });
        }           
    
        private void addStuffToFrame() {    
            JPanel panel = new JPanel(new GridLayout(3,1));
            final JLabel label = new JLabel();
            final JTextField tf = new JTextField(); 
            JButton b = new JButton("calc sting width");
            b.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    FontMetrics fm = label.getFontMetrics(label.getFont());
                    String text = tf.getText();
                    int textWidth = fm.stringWidth(text);
                    label.setText("text width for \""+text+"\": " +textWidth);
                }
            });
            panel.add(label);
            panel.add(tf);
            panel.add(b);
            frame.setContentPane(panel);
        }
    
    
    }
    

提交回复
热议问题