Straightfw
Straightfw

Reputation: 2211

JPanel doesn't disappear after using remove()

I'm programming minesweeper with Java and Swing and am working on what the code should do when user restarts the game with desired dimensions. I have a class MyGrid which has one (int, int) constructor and is an extension of JPanel. It draws the grid and handles what happens with it (clicks, bomb placement and such). So in the game class I have an ActionLister for when user wants to start a new game, I validate the user's input and then I would like to paint a new grid on my JFrame (here called myPane). So I do sth like this:

        myPane.remove(mswGrid);
        MyGrid mswGrid = new MyGrid(nowaSzerokosc, nowaWysokosc);
        myPane.getContentPane().add(mswGrid, BorderLayout.CENTER);
        myPane.repaint();
        myPane.validate();

And while it paints fine the first time, every other time it just paints over or under my previous grid so that when we have 3x3 and then 15x15, you have to resize the window to see those cells and they're painted under the previous 3x3 grid. Why doesn't the grid disappear? I mean - the object is long gone as we create new and so should be the graphics representation thanks to remove(). Why isn't it?

Upvotes: 2

Views: 1365

Answers (1)

StanislavL
StanislavL

Reputation: 57381

Call in this order.

    myPane.revalidate();
    myPane.repaint();

Upvotes: 6

Related Questions