0

While I was debugging earlier, I discovered something a little strange. With the following code, the width of the JDesktopPane changes, seemingly without any interaction, directly or indirectly.

import javax.swing.*;

public class Main
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(960, 640);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setLocationRelativeTo(null);

        JDesktopPane desktop = new JDesktopPane();
        frame.add(desktop);
        System.out.println(desktop.getWidth()); // 0
        frame.setVisible(true);
        System.out.println(desktop.getWidth()); // ~1/2 monitor width
        new JInternalFrame();
        System.out.println(desktop.getWidth()); // monitor width
    }
}

I can understand why the width would change when the JFrame is changed, but why does it change simply because a JInternalFrame is created?

  • 3
    This has a lot to do with how the frame updates and lays outs it contents, layouts aren't always a single step from start position to end position, sometimes, they are done in steps in reaction to different changes over time. It's possible that the frame is been first realised at 960x640 before its realised to its maximised size. You could add a ComponentListener to the frame and output the changes to componentResized events and check the sizes... – MadProgrammer Oct 19 '14 at 20:23
  • 3
    You also get different results when you wrap your code in `SwingUtilities.invokeLater()` which is the proper way to create your GUI since all GUI code should be done on the Event Dispatch Thread (EDT). – camickr Oct 19 '14 at 21:16

0 Answers0