In some cases, the title of my JDialog is too long to fit within the title bar. The preferred size of the dialog is therefore set according to the length of the title.
I used the accepted answer of the question How to set dialog's width relative to the width of its title? but it does not solve my problem.
When running this code:
package test;
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class DialogTitleSize extends JDialog
{
public DialogTitleSize()
{
setModal(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setTitle("This is a very long title. Enough for the preferred size to be extended");
JLabel label;
label = new JLabel("Look and feel: " + UIManager.getLookAndFeel().getClass().getSimpleName());
add(label, BorderLayout.NORTH);
label = new JLabel("Label font: " + UIManager.getDefaults().getFont("Label.font").getSize());
add(label, BorderLayout.SOUTH);
}
@Override
public Dimension getPreferredSize()
{
Dimension result;
result = super.getPreferredSize();
if (getTitle() != null)
{
Font font;
int titleStringWidth;
font = UIManager.getDefaults().getFont("Label.font");
titleStringWidth = SwingUtilities.computeStringWidth(new JLabel().getFontMetrics(font), getTitle());
titleStringWidth += 135;
if (titleStringWidth > result.width)
result.width = titleStringWidth;
}
return (result);
} // getPreferredSize
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
DialogTitleSize dialog;
dialog = new DialogTitleSize();
dialog.pack();
dialog.setVisible(true);
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
} // class DialogTitleSize
I get different results on different environments.
When running directly from within Eclipse 2022-03 on my Windows 10 PC, I get this:
Running the very same code directly from the command line on my Windows 10 PC, the output is as follows:
Finally, when running the code from the command line on a Windows Server 2012 R2, I get this:
I tried adding JDialog.setDefaultLookAndFeelDecorated(true);
before creating the dialog, as suggested within the accepted answer of Font size of JDialog title, but the result doesn't change.
Both my PC and the Windows Server have Java 8 while Eclipse runs Java 18.
Any idea how to solve this problem?