I need to make a button that will display different things depending on the state if the app. So for example if nothing has been opened its title will be “Lesson Plans” and if project B is open it will be “project B Lesson Plan”, I am using the java.awt.Button class for this. My question, is there a way to determine how big the button should be to fit the given text. For example can I somehow get the width of each character in the given font used by the button then multiply this by the characters in the title I want to use? How would I get this character width or is there some better way? Thanks!
Share
Measuring widths of individual characters in particular fonts (not all characters are the same width) gets complicated, especially if you want to take into account the spaces between characters, and add some margin either side so they don’t butt up against the edges of the button. (N.B. Others have provided a few ways of doing this more simply than I realized was possible!)
Much better/more usual solution is to let Java do the work for you. If you’re using using a
java.awt.Button(orjavax.swing.JButton), then it will usually automatically size to the text on it. If your particular button is behaving strangely, then you probably have a layout problem. Check the section of the Java tutorial on Layout Managers for more information.As an example (in Swing, rather than AWT – sorry!), these two buttons end up being the right size for the text on them:
If you really do want the size, rather than just letting Java do its best, then I would recommend calling
button1.getPreferredSize()andbutton2.getPreferredSize()after the call toframe.pack().