How to replace JPanel with another JPanel

前端 未结 6 1688
有刺的猬
有刺的猬 2021-01-05 10:46

I want to replace a Jpanel with another one in a JFrame I already search and try my code but nothing\'s happen this is my code :

public class Frame extends          


        
6条回答
  •  悲&欢浪女
    2021-01-05 11:26

    Assume you have a function, generatePanel() that returns a JPanel that you save in an instance variable of type JPanel:

    private JPanel panelWithDynamicContent;
    

    Assume you have already placed that JPanel into a container, perhaps at a specific index within that other container and want to preserve the order of the components within that container. Instead of destroying everything using removeAll(), I prefer a more precise approach that replaces only the component that needs to be replaced:

    private void replacePanel(){
       Container parent = this.panelWithDynamicContent.getParent();
       int index = parent.getComponentZOrder(this.panelWithDynamicContent);
       // remove the old edition of the panel
       parent.remove(this.panelWithDynamicContent);
       // generate the replacement panel
       this.panelWithDynamicContent = generatePanel();
       // place the replacement panel in the same relative location as the one it is replacing
       parent.add(this.panelWithDynamicContent, index);
    
       // must call both of these, in the correct order
       parent.validate();
       parent.repaint();
    }
    

提交回复
热议问题