有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么swing gui的行为很奇怪?

我刚开始在扫雷舰上开发Java应用程序。其想法是在JFrame中使用GridLayout JPanel。但在执行程序后,我得到了一些奇怪的窗口。左上角有一个奇怪的灰色角落。而且瓷砖也不全露出来。不知怎的,把鼠标悬停在他们身上就会显示出来

JFrame frame = new JFrame("MineSweeper");
        JPanel panel = new JPanel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(600, 540));
        frame.add(panel);
        panel.setPreferredSize(new Dimension(540, 540));
        panel.setLayout(new GridLayout(numRows, numCols));
        
        for(int y=0; y<numRows; y++) {
            for(int x=0; x<numCols; x++) {
                Tile t = new Tile(x, y);        
                panel.add(t);
                field[y][x] = t;
                
            }
        }
        
        frame.pack();
        panel.setVisible(true);
        frame.setVisible(true);

这个节目产生了这种令人憎恶的丑恶现象。 enter image description here

如何使网格同时显示?以及如何去除左上角的灰色斑点

注意:我刚开始使用Swing GUI,所以我几乎什么都不知道。尽量不要让事情变得复杂


共 (1) 个答案

  1. # 1 楼答案

    我试图重写这个布局代码,一点也不复杂:)

    public class MineSweeper extends JFrame {
    
        public static void main(String[] args) {
            int columns = 10, rows = 10;
            int cellSize = 50;
    
            JPanel board = new JPanel();
            board.setLayout(new GridLayout(rows, columns));
            for (int i = 0; i < columns; i++) {
                for (int j = 0; j < rows; j++) {
                    board.add(new Button("x"));
                }
            }
    
            MineSweeper mineSweeper = new MineSweeper();
            mineSweeper.setDefaultCloseOperation(EXIT_ON_CLOSE);
            mineSweeper.setContentPane(board);
            mineSweeper.setSize(cellSize * columns, cellSize * rows);
            mineSweeper.setResizable(false);
            mineSweeper.setVisible(true);
        }
    }
    

    enter image description here

    所以我认为你的问题可能是关于setPreferredSize()呼叫,或者你的Tile