Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a JPanel with another while the program is running

Tags:

java

swing

The code has a JPanel with an inner JPanel that displays awt drawing. Upon mouseclick the inner JPanel is to be replaced by one of its polymorphic siblings. This code isn't replacing the jPanel.


class ContentPanel extends JPanel {

  private GraphicPanel graphicPanel;

  public ContentPanel(GraphicPanel graphicPanel) {
    this.graphicPanel = graphicPanel;
    add(this.graphicPanel);

  public void setGraphicPanel(GraphicPanel graphicPanel) {
    this.graphicPanel = graphicPanel;

// invalidate(); // revalidate(); // repaint(); }

Setting the graphicPanel to a polymorphic relative doesn't cause any errors, it just isn't painting the new graphicPanel. Using cardLayout is not preferred, there must be a cleaner way. How to proceed?

like image 317
comp sci balla Avatar asked Nov 13 '10 20:11

comp sci balla


1 Answers

in setGraphicPanel, you need to remove the current graphicPanel and add the new one. THEN call revalidate.

something like this:

public void setGraphicPanel(GraphicPanel graphicPanel) {
    this.removeAll();
    this.graphicPanel = graphicPanel;
    this.add(graphicPanel);
    this.revalidate();   
}

Although CardLayout was designed to do just this thing. Are you sure you don't want to use CardLayout?

like image 52
Steve McLeod Avatar answered Nov 14 '22 23:11

Steve McLeod