Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

calculate jbutton width

kvasoOct 3 2010 — edited Oct 4 2010
Hi, I am trying to calculate JButton's width so that the text inside can be properly displayed.
The point is, that I've got one JButton which text can be changed and I want to set the width of this button, so it should not need to be resized anymore
Here is my method:
       
private int getButtonMaxWidth(){
 JButton butt = new JButton(); //I create one sample JButton, so I can get FontMetrics of it
        FontMetrics fm = butt.getFontMetrics(butt.getFont());
        int maxWidth = 0;
        for (String s : buttonStrings) {
            maxWidth = Math.max(maxWidth, fm.stringWidth(s));
        }
        return maxWidth + butt.getInsets().left + butt.getInsets().right;
}
the problem is, it does not work properly: it sets jbutton's width to half as it should be...
Could you advise me some solution?
thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 1 2010
Added on Oct 3 2010
6 comments
503 views