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?