简体   繁体   中英

Resizing JButtons and other components according to text

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 this be turned into a utility method?

FontMetrics metrics = getFontMetrics( font );
int width = metrics.stringWidth( string );

PS: No layout manager is being used.

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.

I had the same problem, even when using a layout manager (BorderLayout). But in my case a simple call to layoutContainer() of the associated layout manager and then a repaint() on the JFrame was sufficient for changing the width of the button.

button1.setText("New Label that differs in width");
// button1 is inside the container horizontalBox
horizontalBox.getLayout().layoutContainer(horizontalBox);
repaint(); // on the containing JFrame

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM