1

I have tried running the following code. The GUI constructor that I call is from a class that extends JPanel.

As you can see I have already tried using the pack() method.

The window that appears is smaller than 500x500. How do I fix this?

import java.awt.Dimension;
import javax.swing.JFrame;

public class Main extends JFrame {

    public Main(){


        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setPreferredSize(new Dimension(500, 500));

        setTitle("Chess");
        
        GUI gui = new GUI();
        setContentPane(gui);

        pack();

        setVisible(true);

    }



    public static void main(String[] args){

        Main main = new Main();
        main.repaint();
    }

Already tried using pack().

Papershine
  • 4,995
  • 2
  • 24
  • 48
LMG
  • 13
  • 2

1 Answers1

2

Because the frame size includes the frame borders, title bars, and headers which are especially large and take up extra space. Set the size of a JPanel and add that to the frame and draw and add components to the panel. And don't forget to call frame.pack().

WJS
  • 36,363
  • 4
  • 24
  • 39
  • also you should probably use setSize() instead as per [this](https://stackoverflow.com/questions/1783793/java-difference-between-the-setpreferredsize-and-setsize-methods-in-compone) – Guy Lawrence-Downs Nov 29 '22 at 15:56
  • @GuyLawrence-Downs The default parent (`JFrame` in this case) layout manager is `BorderLayout` So `setPreferredSize` should be used. In fact, it is customary to override `getPreferredsSize()` and have it return the size. – WJS Nov 29 '22 at 16:00
  • are they not talking about the size of the JFrame not the gui panel? I understand that reducing the size of the panel would also have the same affect. – Guy Lawrence-Downs Nov 29 '22 at 16:04
  • I thought the OP was lamenting the fact that the frame did not have the space designated by the dimensions. – WJS Nov 29 '22 at 17:28