Reputation: 14439
I have following code that is used to compute dialog title width.
FontRenderContext frc = new FontRenderContext(null, true, true);
TextLayout tl = new TextLayout(getTitle(), getFont(), frc);
double w = tl.getPixelBounds(null, 0, 0).getWidth();
However for some reason text width is computed wrongly. I checked this code for computing radio button label text width and it worked correctly. My main concern is about dialog font, I am not sure if I correctly get it.
For example for title test
computed width is 20
however actual width is 23
. The longer string is the bigger difference between computed and actual widths.
Upvotes: 1
Views: 932
Reputation: 3585
You're getting a wrong result because the dialog title and the font it's using are native resources.
If you're application is Windows-only, you can get the width with this code:
Font f = (Font)Toolkit.getDefaultToolkit().getDesktopProperty("win.frame.captionFont");
Graphics gr = getGraphics();
FontMetrics metrics = gr.getFontMetrics(f);
int width = metrics.stringWidth(getTitle());
Otherwise try to get the FontMetrics from the title bar's font:
Container titleBar = (Container) dialog.getLayeredPane().getComponents()[1];
FontMetrics metrics = titleBar.getFontMetrics(titleBar.getFont());
int width = metrics.stringWidth(getTitle());
If it's to dynamically set the width of the dialog, you also need to take into account the LaF spacing and the borders. Try this:
// This is the space inserted on the left of the title, 5px in Metal LaF
width += 5;
// This is the space for the close button, LaF dependent.
width += 4;
// Add the borders
width += dialog.getWidth() - dialog.getContentPane().getWidth();
// Finally set the size
dialog.setSize(new Dimension(width, dialog.getPreferredSize().height));
Hopefully this will work. If you wonder where the numbers come from, they're in the JDK source code.
Upvotes: 5