How to repaint a JPanel after have drawn on it?

Aerozeek picture Aerozeek · Dec 8, 2010 · Viewed 59k times · Source

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

Answer

Cameron Skinner picture Cameron Skinner · Dec 8, 2010

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

EDIT: Changed from invalidate to revalidate