Resizing JButtons and other components according to text

前端 未结 2 835
不思量自难忘°
不思量自难忘° 2021-02-09 05:27

How do you resize a JButton at runtime so it adapts to the text given by setSize? I\'ve done some searching and this is the code I\'ve come up with so far. Could th

2条回答
  •  独厮守ぢ
    2021-02-09 06:26

    You need to use setPreferredSize() on the component. Then, to resize it, call setBounds().

    I would probably subclass the button, and override the setText(String text) method to include the resizing code.

    @Override
    public void setText(String arg0) {
        super.setText(arg0);
        FontMetrics metrics = getFontMetrics(getFont()); 
        int width = metrics.stringWidth( getText() );
        int height = metrics.getHeight();
        Dimension newDimension =  new Dimension(width+40,height+10);
        setPreferredSize(newDimension);
        setBounds(new Rectangle(
                       getLocation(), getPreferredSize()));
    }
    

    For testing, I did this in the constructor of my new JButton subclass:

    public ResizeToTextButton(String txt){
        super(txt);
        addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                setText(JOptionPane.showInputDialog("Text"));
            }
        });
    }
    

    So, whenever I clicked on the button I could change the text and see if it resized properly.

提交回复
热议问题