10

I have a component that inherits from JPanel, I draw a grid on it. Now I have a JComboBox and I want the user to be able to choose the grid size here and then press a button to make the grid change (repaint the grid).

The thing is that it paints the initial grid, but once the user choses a grid size from the JComboBox and clicks the button, nothing happens. I have to minimize the form and then restore it again to see the changes.

Any Ideas? The Code is below.

The Component:

public class Board extends JPanel {
    ...

    protected void paintComponent(Graphics og) {
        super.paintComponent(og);
        ...
        }
    }    
}

Main Class

public class Main extends javax.swing.JFrame {
...

public Main() {                                   //This works great.
    board = new Board( ... );
    somePanel.add(board, BorderLayout.CENTER);

}

public void someButtonActionPerformed(Event e) { //This is not working

    somePanel.remove(board);
    board = new Board( ... );
    somePanel.add(board);
    somePanel.invalidate()
    board.repaint();
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Aerozeek
  • 495
  • 1
  • 3
  • 11

1 Answers1

20

Try calling somePanel.revalidate(). That will tell the AWT that you have changed the component tree.

EDIT: Changed from invalidate to revalidate

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
  • 1
    Thank you for your answer. I've tried that already, didn't worked :( J. – Aerozeek Dec 08 '10 at 21:52
  • 1
    You might want to update your code in the question to show that. Is the `someButtonActionPerformed` method actually being called? Have you added a `System.out.println` to check? – Cameron Skinner Dec 08 '10 at 21:54
  • Yes. The method is called, no doubt of that. The fact is that it does what it should do, just that it doesn't repaint until I minimize and then restore the window. I've been working around this all day long and nothing. – Aerozeek Dec 08 '10 at 21:57
  • Hmm. Well, the code you posted looks fine (apart from the `revalidate`). Is there any more relevant code that you could post? Maybe there's something else going on. – Cameron Skinner Dec 08 '10 at 21:59
  • 1
    Whoops! I meant to say `revalidate` in my answer, not `invalidate`. That could be the problem. – Cameron Skinner Dec 08 '10 at 22:00
  • 1
    That was exactly the problem! Thank you my friend you were extremely useful. J. – Aerozeek Dec 08 '10 at 22:03
  • 1
    No trouble. I'd recommend reading up on `invalidate`, `validate` and `revalidate` if you haven't already. They can be tricky to get right. – Cameron Skinner Dec 08 '10 at 22:04