tags:

views:

437

answers:

2

Let's say I have a JButton, and I want it to be big enough to fit a string of 8 "M" characters, regardless of the string that is actually assigned to it and the font size, without using elipsis.

The JButton has to have precisely this size, no more, no less. Layout manager in use is GridBagLayout.

I tried overwriting the getPreferredSize() method and perform a calculation using the string and the current font of the system. The calculation gives me back some sensible value, however, I have no idea how to set the preferred size in such a way that the borders are also considered.

I tried to get the insets of the component, but they are all 0's.

This is the code of my method:

public void getPreferredSize() {
        Dimension d = super.getPreferredSize();

        // Geometry width indicates how many characters must fit
        char[] pad = new char[propGeometryWidth];
        Arrays.fill(pad, 'M');
        String tmpTemplateString = new String(pad);

        FontMetrics tmpMetrics = getFontMetrics(getFont());
        Rectangle2D tmpR2D = tmpMetrics.getStringBounds(tmpTemplateString, getGraphics());

        int tmpWidth = (int)tmpR2D.getWidth();
        int tmpHeight = (int)(tmpR2D.getHeight() * propGeometryHeight + tmpR2D.getHeight());

        // We need to take into consideration borders and padding!
        Insets insets = getInsets();

        Dimension tmpSize = new Dimension(tmpWidth + insets.left + insets.right, tmpHeight + insets.top + insets.bottom);
        return tmpSize;
}

I get the feeling that this might be related to the fact that my component is not realized yet, but I am completely unsure how I could solve this issue. Am I approaching this problem from the wrong perspective?

+2  A: 

I think you may actually be doing it right already. From the Javadoc for getInsets():

If a border has been set on this component, returns the border's insets; otherwise calls super.getInsets.

A freshly-created JButton for me shows insets of java.awt.Insets[top=5,left=17,bottom=5,right=17] with the default look and feel, and java.awt.Insets[top=4,left=16,bottom=4,right=16] with the Windows look and feel. Are you using a custom look and feel, perhaps?

Michael Myers
+1  A: 

I found the reason for my problem. The problem is that I had a panel with a JButton inside, and I overwrote the method on the panel (There is a relatively complex hierarchy of classes). Then, of course, the insets for the Panel are all set to 0. After getting the insets for the button, as stated by Mr. Mmyers, it all works great.

Mario Ortegón