Ensuring that JButton Can Match a String of Given Length

Let's say I have a JButton, and I want it to be large enough to match a string of 8 characters "M", no matter what string is actually assigned to it and the font size, without using elipsis.

JButton should have this particular size, no more, no less. The layout manager uses GridBagLayout.

I tried rewriting the getPreferredSize () method and doing the calculation using the string and the current system font. The calculation gives me some reasonable value, however, I do not know how to set the preferred size so that the borders are also taken into account.

I tried to get component insertions, but they are all 0.

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 may be due to the fact that my component is not yet implemented, but I'm completely not sure how I can solve this problem. Am I approaching this problem from the wrong point of view?

+4
source share
2 answers

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

If a border is set on this component, the border inserts are returned; otherwise calls super.getInsets .

The newly created JButton for me shows inserts java.awt.Insets[top=5,left=17,bottom=5,right=17] with a standard look and java.awt.Insets[top=4,left=16,bottom=4,right=16] with the appearance of Windows. Are you using a custom look, perhaps?

+2
source

I found the cause of my problem. The problem is that I had a panel with JButton inside, and I rewrote the method on the panel (there is a relatively complex class hierarchy). Then, of course, for an insert for Panel, it is still 0. After receiving the insert for the button, as Mr. Mmiers stated, all this works fine.

+1
source

All Articles