2

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?

Straightfw
  • 2,143
  • 5
  • 26
  • 39
  • 2
    Consider using a `CardLayout` instead ([e.g.](http://stackoverflow.com/questions/5665156/calling-awt-frame-methods-from-subclass/5786005#5786005)). For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Jan 11 '13 at 11:59
  • @GuillaumePolet - a JFrame object in which both the menu and the playing grid sit. – Straightfw Jan 11 '13 at 14:04

1 Answers1

5

Call in this order.

    myPane.revalidate();
    myPane.repaint();
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • Unfortunately, it doesn't help - it still can't pass 3x3->15x15 test with just the same symptoms. – Straightfw Jan 11 '13 at 11:46
  • 2
    @Straightfw no, this is correct suggestion, issue must be somewhere on your side, right concept is by using CardLayout with pack() for container, then you'll only to switch betweens views – mKorbel Jan 11 '13 at 12:04
  • @mKorbel - I'm not saying it's not, just that it doesn't work "as-is". Guess I'll just have to revise the whole code as the culprit's elsewhere. – Straightfw Jan 11 '13 at 14:04
  • OK, spotted it. My whole coding of the object MyGrid was poor so I just refactored it from an object inheriting from JPanel to a "regular" object which creates the JPanel in its body and lets you get that panel via a simple getter. Works like a charm now :) – Straightfw Jan 11 '13 at 14:40