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:

okButton.setText(okLabel);
        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?

Recommended Answers

All 3 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.