Kuba Spatny
Kuba Spatny

Reputation: 26978

Swing - JFrame is sometimes bigger than preffered size

I am writing an a snake game, but there's a small problem. SOMETIMES there's a little gap between the panel and the frame. I really have no idea what could be the problem as it appears so irregularly.

The gap is on the right and bottom. This time, it is displayed correctly. SSCCE:

public class Game {

static JFrame frame = new JFrame("The Snake Game");
static Game game = new Game();
JPanel cards;
static JPanel card1 = new JPanel();

private Game() {    
}

public void addComponentToPane(Container pane) {

    // CARD 1

    card1.setLayout(null);
    card1.setPreferredSize(new Dimension(600, 625));        

    CardLayout cl = new CardLayout();        
    cards = new JPanel(cl);
    cards.add(card1);

    pane.add(cards, BorderLayout.CENTER);
}

private static void createAndShowGUI() {

    game.addComponentToPane(frame.getContentPane());
    frame.setResizable(false);      
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.pack();

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

} 

public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });

} // end of main

}

Upvotes: 1

Views: 1602

Answers (3)

Vapto
Vapto

Reputation: 11

I encounter the same problem today. After a little bit of Googling, I couldn't find any good answer. Kuba gave a good hint and the problem is finally resolved. I guess this issue is caused by the delay of the setResizable(false) function and hence it happens occasionally. My solution is adding a short hold after calling setResizable.

setResizable(false);
try {
    Thread.sleep(200);
} catch (InterruptedException e) {
    e.printStackTrace();
}

Upvotes: 1

Kuba Spatny
Kuba Spatny

Reputation: 26978

Okay, I know this is a disgusting way to do it. But in the question JFrame isResizable(false) sizing issue is said: "You can reset it by call JFrame#pack after the calling JFrame#setResizable". So I thought, why not reset it twice?!

Code:

private static void createAndShowGUI() {

  game.addComponentToPane(frame.getContentPane());
  frame.setResizable(false);      
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  frame.pack();

  if(frame.getContentPane().getWidth() > 600){
        frame.pack();
  }

  frame.setLocationRelativeTo(null);
  frame.setVisible(true);
}

So calling the method pack() for the second time when the width is greater than my preferred size seems to resolve the problem.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347184

Try calling setResizable AFTER you call pack

For some reason, doing it the other way seems to add about 10-20 pixels to the width and height.

If that doesn't work, call setResizable AFTER the frame has being made visible

Upvotes: 2

Related Questions