Added panel not showing up in frame (Java)

Viewed 78

I'm working on making a battleship game board using swing in java. I've added the panel (i.e. the grid or the game board) to the window but it still won't show up. I've pasted the code below. Any help is appreciated. Thanks.

public class board {

private static JFrame window;
private static JPanel[][] grid;

public static void main(String[] args) {
    window = new JFrame();
    window.setTitle("GAME BOARD");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    grid = new JPanel[10][10];
    for (int i =0; i< 10; i++) {
        for (int j =0; j< 10; j++) {
            grid[i][j] = new JPanel();
            grid[i][j].setBackground(Color.white);
            grid[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
            grid[i][j].setPreferredSize(new Dimension(25,25));
            window.add(grid[i][j]);
        }
    }
    window.pack();
    window.setVisible(true);
}

}

2 Answers

By default calling JFrame#add() will add to the JFrames contentPane which has a default layout of BorderLayout.

Have a read on A Visual Guide to Layout Managers. You probably want to either use a GridLayout or FlowLayout depending on your needs.

I'd also suggest overriding getPreferredSize and returning the dimensions as opposed to calling setPreferredSize.

You then would do something like this:

// this jpanel will hold the all grid jpanels could also use new FlowLayout()
JPanel container = new JPanel(new GridLayout(10,10));
grid = new JPanel[10][10];
    for (int i =0; i< 10; i++) {
        for (int j =0; j< 10; j++) {
           grid[i][j] = new JPanel() {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(25, 25);
                }
            };
            ...
            container.add(grid[i][j]);
        }
    }

window.add(container);
window.pack();
window.setVisible(true);

Have a look at this question which is also about creating a layout for a battleship game. I'd suggest using something more lightweight and easier to customize like JLabel to represent each square.

enter image description here

You may also want to read up on The Event Dispatch Thread

Essentially all Swing components should be created on the EDT via SwingUtilities.invokeLater(...):

import javax.swing.SwingUtilities;

public class TestApp {

    public TestApp() {
        createAndShowGui();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TestApp::new);
    }

    private void createAndShowGui() {
         // create JFrame and other Swing components here
    }
}

You need to set your frame size

window.setPreferredSize(new Dimension(800, 800));
Related