How to replace JPanel with another while the program is running

The code has a JPanel with an internal JPanel that displays an awt drawing. On mouseclick, the internal JPanel must be replaced by one of its polymorphic siblings. This code does not replace 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 ();   }

code>

Installing a graphic object in a polymorphic relative does not cause any errors, it just does not draw a new graphic panel. Using cardLayout is not preferred; there should be a cleaner way. How to act?

+5
source share
1 answer

in setGraphicPanel, you need to delete the current graphic panel and add a new one. Then activate the call.

something like that:

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

CardLayout , . , CardLayout?

+3

All Articles