I have a class which extends JDialog which by default has some text on it and a couple of buttons. Most of the instance of the buttons are "Ok" and "Cancel" so the two buttons have their bounds set. If I try to change the label on the Ok button to something longer such "To Engage Plan" the text is truncated since the default size is too small. I want to be able to set the size of button based on its current insets, margins etc and use the new string to calculate the button width. I have tried:

        Graphics g = okButton.getGraphics();
        FontMetrics f = g.getFontMetrics();
        Insets inset = okButton.getMargin();
        Dimension d = okButton.getSize();
        int size = f.stringWidth(okLabel);
        okButton.setSize(size+inset.left+inset.right, d.height);

This doesn't work as the default width is 120 and the calculation size+inset.left+inset.right = 99 in the case of the string "To Engage Plan". Any idea how to increase the button size?

6 Years
Discussion Span
Last Post by minghia

Try using just getInsets() instead of getMargin()

String label = "Really Super Extra Long String Here";
int len = jButton1.getFontMetrics(jButton1.getFont()).stringWidth(label);
jButton1.setSize(len + 2*jButton1.getInsets().left, jButton1.getHeight());

sure there is better to use a proper LayoutManager

Font font = jButton1.getFont();
FontMetrics fontMetrics = jButton1.getFontMetrics(font);
maxWidth = SwingUtilities.computeStringWidth(fontMetrics, text);

The reason that I am using AbsoluteLayout is because I am simulating an existing interface and none of the windows are resizeable. I am trying to mimic the original user interface as closely as possible.

Of course once I change to using getInsets rather getMargin it all worked as expected. Thanks everyone for their help.

Edited by minghia: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.