错误的字符串宽度

mic*_*nko 1 java swing

我有以下代码用于计算对话框标题宽度.

FontRenderContext frc = new FontRenderContext(null, true, true);
TextLayout tl = new TextLayout(getTitle(), getFont(), frc);
double w = tl.getPixelBounds(null,  0, 0).getWidth();
Run Code Online (Sandbox Code Playgroud)

但是由于某种原因,错误地计算了文本宽度.我检查了这段代码,用于计算单选按钮标签文本宽度,并且它正常工作.我主要担心的是对话框字体,我不确定我是否正确得到它.

例如,对于标题test计算的宽度,20实际宽度是23.字符串越长,计算宽度和实际宽度之间的差异越大.

Tra*_*lio 5

您得到了错误的结果,因为对话框标题和它使用的字体是本机资源.

如果您的应用程序仅限Windows,则可以使用以下代码获取宽度:

Font f = (Font)Toolkit.getDefaultToolkit().getDesktopProperty("win.frame.captionFont");  
Graphics gr = getGraphics();  
FontMetrics metrics = gr.getFontMetrics(f);  
int width = metrics.stringWidth(getTitle());  
Run Code Online (Sandbox Code Playgroud)

否则尝试从标题栏的字体中获取FontMetrics:

Container titleBar = (Container) dialog.getLayeredPane().getComponents()[1];
FontMetrics metrics = titleBar.getFontMetrics(titleBar.getFont());
int width = metrics.stringWidth(getTitle());
Run Code Online (Sandbox Code Playgroud)

如果要动态设置对话框的宽度,还需要考虑LaF间距和边框.试试这个:

// 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));
Run Code Online (Sandbox Code Playgroud)

希望这会奏效.如果你想知道数字来自哪里,它们就是JDK源代码.