Added panel not showing up in frame (Java)

寵の児 提交于 2021-01-05 07:22:18

问题


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);
}

}


回答1:


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.

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
    }
}



回答2:


You need to set your frame size

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


来源:https://stackoverflow.com/questions/65436163/added-panel-not-showing-up-in-frame-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!