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.setPreferredSize(new Dimension(600, 540));
        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);        
                field[y][x] = t;

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.


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.setSize(cellSize * columns, cellSize * rows);

enter image description here

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

Source: stackoverflow