2

我有一个 JDialog,里面只有几个组件。我想让对话框尽可能小。目前我正在使用 pack()。这会产生意想不到的效果,即大大减小了对话框的宽度,以至于标题不再完全在视图中。我希望对话框的宽度始终足够大,以使标题始终完全可见。

我正在使用摆动。我意识到标题栏外观/字体是由操作系统决定的。我宁愿坚持摆动,所以目前我计划根据 JLabel 的字体计算标题字符串的宽度。然后我将我的一个组件的最小宽度设置为等于该值。

有没有更好的方法来打包 JDialog 同时保持其标题可见?

4

2 回答 2

6
 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()));

    }
}

编辑:在阅读链接中的垃圾神帖子后,我调整了我的解决方案以覆盖 getPreferredSize 方法。我认为这种方式比我之前的静态方法要好。使用静态方法,我不得不在 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;
        }

    };
于 2012-09-20T17:38:15.357 回答
1

1)FontMetrics用于找出标题的宽度

2) 向这个值添加一个代表窗口图标和 X(关闭)按钮的数字(你应该猜到了)。

3) 使用上述值设置对话框的宽度。

您找不到所需的确切宽度尺寸,但这是一种很好的猜测方法。

于 2012-09-20T17:24:49.613 回答