Why is the swing gui behaving strange?

Tags: , ,



I just started making my Java application on Minesweeper. The idea is a GridLayout JPanel inside a JFrame. But after executing the program I get some weird window. There is this strange gray corner on the upper left corner. And the tiles don’t all show. Somehow hovering the mouse over them shows.

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

The program produced this ugly abomination. enter image description here

How to make the grid all show at once? And how to remove that gray spot on upper left corner.

Note: I just started Swing GUI so I know practically nothing. Try not to make it to complicated.

Answer

I have tried to rewrite this layout code, not complicated at all 🙂

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

So I think may be your problem is about setPreferredSize() call, or your Tile class.



Source: stackoverflow