Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repaint a JPanel after have drawn on it?

Tags:

java

swing

jpanel

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();
}
like image 646
Aerozeek Avatar asked Dec 08 '10 21:12

Aerozeek


People also ask

How do you delete a panel in Java?

SwingUtilities. invokeLater(new Runnable() { public void run() { frame. getContentPane(). remove(panel1); frame.


1 Answers

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

EDIT: Changed from invalidate to revalidate

like image 65
Cameron Skinner Avatar answered Oct 30 '22 14:10

Cameron Skinner