如何设置对话框相对于标题宽度的宽度?

Jus*_*man 2 java swing jframe jdialog width

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

我正在使用秋千.我意识到标题栏的外观/字体是由OS决定的.我宁愿坚持使用swing,所以目前我正计划根据JLabel的字体计算标题字符串的宽度.然后我将我的一个组件的最小宽度设置为相等.

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

Jus*_*man 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()));

    }
}
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)