简体   繁体   中英

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

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM