简体   繁体   English

如何在程序运行时将JPanel替换为另一个JPanel

[英]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. 该代码有一个JPanel,内部JPanel显示awt绘图。 Upon mouseclick the inner JPanel is to be replaced by one of its polymorphic siblings. 鼠标点击后,内部JPanel将被其中一个多态兄弟姐妹取代。 This code isn't replacing the jPanel. 此代码不替换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. 将graphicPanel设置为多态相对不会导致任何错误,它只是不绘制新的graphicPanel。 Using cardLayout is not preferred, there must be a cleaner way. 使用cardLayout不是首选,必须有一个更清洁的方式。 How to proceed? 如何进行?

in setGraphicPanel, you need to remove the current graphicPanel and add the new one. 在setGraphicPanel中,您需要删除当前的graphicPanel并添加新的。 THEN call revalidate. 然后调用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. 虽然CardLayout只是为了这件事而设计的。 Are you sure you don't want to use CardLayout? 你确定你不想使用CardLayout吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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