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 );
P.S: No layout manager is being used.
You need to use
setPreferredSize()on the component. Then, to resize it, callsetBounds().I would probably subclass the button, and override the
setText(String text)method to include the resizing code.For testing, I did this in the constructor of my new
JButtonsubclass:So, whenever I clicked on the button I could change the text and see if it resized properly.