Java Swing JPanel size not working

217 views Asked by At
    frame = new JFrame();
    frame.setTitle("Chess Legends");
    frame.setBounds(100, 100, 810, 830);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //game panel
    panelGame = new JPanel();
    panelGame.setBackground(new Color(0, 0, 0));
    frame.getContentPane().add(panelGame, BorderLayout.CENTER);
    panelGame.setLayout(null);

    //board panel
    panelBoard = new JPanel();
    panelBoard.setBackground(new Color(255, 255, 255));
    panelBoard.setBounds(5, 5, 800, 800);
    panelGame.add(panelBoard);

This is my code. I want the panelGame to fill the entire frame. Then I want the panelBoard to take upp 800x800 size inside the panelGame. But my panelBoard seems to be too big.

The frame is already larger than the bounds of the panelBoard,Yet when the GUI launches.. my panelBoard extends outside the frame. Why?

1

There are 1 answers

0
camickr On BEST ANSWER

my panelBoard extends outside the frame. Why??

A frame has decorations (border, titlebar) which take up space.

Don't use a null layout and don't try to micro manage the size. Instead use layout manager and pack() the frame and let the layout managers determine the size.

If you want the panel board to be 800 x 800, then override the getPreferredSize() method to return that Dimension.

Then you do something like:

PanelBoard panelBoard = new PanelBoard(); // with overridden getPreferredSize()

JPanel panelGame = new JPanel( new BorderLayout() );
panelGame.setBorder( new EmptyBorder(5, 5, 5, 5) );
panelGame.add( panelBoard );

frame.add( panelGame );
frame.pack();
frame.setVisible();