1

When working on my mac laptop I have recently noticed that my frame sometimes shrinks when the program starts. It is about 70-90% that it does shrink.

It works as expected on a PC but not on any mac I have tried it on. I have tried to narrow it down a bit (to the code below) but from here I can't find any reason for it not working. Some friends of mine think it might have something to do with mac's own window manager. I don't know.

I am fairly new to this, just FYI.

public class Worms extends JFrame{

    public static void main(String[] args) {
        new Worms();
    }

    private JButton startGame;
    public Worms(){
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        Container contentPane = this.getContentPane();
        //if i change it so it uses a new dimension not "screenSize" it works
        contentPane.setPreferredSize(screenSize);


        JPanel menu = new JPanel();

        startGame = new JButton("Start Game"); 
        menu.add(startGame);//or if i remove this button it also works
        this.add(menu);


        this.pack();
        this.setVisible(true);
    }
}

It starts in "fullscreen" than it shrinks down to the left corner. If I drag it back to normal size it works as normal.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24

1 Answers1

3
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

Container contentPane = this.getContentPane();
//if i change it so it uses a new dimension not "screenSize" it works
contentPane.setPreferredSize(screenSize);

The content pane should not have the preferred size set to the screen size. That is too large, and does not account for the frame decorations or 'chrome'.

Here is a different approach that should work reliably across systems. It sets the extended sate of the frame.

import java.awt.*;
import javax.swing.*;

public class Worms extends JFrame{

    public static void main(String[] args) {
        new Worms();
    }

    private JButton startGame;
    public Worms(){
        JPanel menu = new JPanel();

        startGame = new JButton("Start Game"); 
        menu.add(startGame);
        this.add(menu);

        this.pack();
        // this should do what you seen to want
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        // this is just polite..
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setVisible(true);
    }
}

Note that Swing / AWT GUIs should be created & updated on the Event Dispatch Thread. The example above does not add that, for the sake of simplicity.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433