public static void adjustWidthForTitle(JDialog dialog)
{
// make sure that the dialog is not smaller than its title
// this is not an ideal method, but I can't figure out a better one
Font defaultFont = UIManager.getDefaults().getFont("Label.font");
int titleStringWidth = SwingUtilities.computeStringWidth(new JLabel().getFontMetrics(defaultFont),
dialog.getTitle());
// account for titlebar button widths. (estimated)
titleStringWidth += 110;
// set minimum width
Dimension currentPreferred = dialog.getPreferredSize();
// +10 accounts for the three dots that are appended when the title is too long
if(currentPreferred.getWidth() + 10 <= titleStringWidth)
{
dialog.setPreferredSize(new Dimension(titleStringWidth, (int) currentPreferred.getHeight()));
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:在链接中阅读trashgod的帖子后,我调整了我的解决方案以覆盖getPreferredSize方法.我认为这种方式比我之前的静态方法更好.使用静态方法,我不得不在pack()三明治中调整它.包(),调节(),pack()的.这个wasy不需要特别考虑pack().
JDialog dialog = new JDialog()
{
@Override
public Dimension getPreferredSize()
{
Dimension retVal = super.getPreferredSize();
String title = this.getTitle();
if(title != null)
{
Font defaultFont = UIManager.getDefaults().getFont("Label.font");
int titleStringWidth = SwingUtilities.computeStringWidth(new JLabel().getFontMetrics(defaultFont),
title);
// account for titlebar button widths. (estimated)
titleStringWidth += 110;
// +10 accounts for the three dots that are appended when
// the title is too long
if(retVal.getWidth() + 10 <= titleStringWidth)
{
retVal = new Dimension(titleStringWidth, (int) retVal.getHeight());
}
}
return retVal;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1750 次 |
| 最近记录: |