添加的面板未显示在框架中 (Java)

Added panel not showing up in frame (Java)

我正在 java 中使用 swing 制作战舰游戏板。我已经将面板(即网格或游戏板)添加到 window 但它仍然不会显示。我已经粘贴了下面的代码。任何帮助表示赞赏。谢谢

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

}

您需要设置帧大小

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

默认调用 JFrame#add() 将添加到 JFrames contentPane,其默认布局为 BorderLayout.

根据您的需要阅读 A Visual Guide to Layout Managers. You probably want to either use a GridLayout or FlowLayout

我还建议覆盖 getPreferredSize 并返回维度而不是调用 setPreferredSize.

然后你会做这样的事情:

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

看看这个问题也是关于的。我建议使用更轻量级且更易于自定义的内容,例如 JLabel 来表示每个正方形。

您可能还想阅读 The Event Dispatch Thread

基本上所有 Swing 组件都应该通过 SwingUtilities.invokeLater(...):

在 EDT 上创建
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
    }
}