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?
source share