简体   繁体   中英

New JFrame Being Created When I Add Content Pane

I don't know why but when I add a content pane it creates a new JFrame window instead of replacing the old content pane on the same window. Thank you, my code follows below: I have a public void (container pane). This is what I'm adding to the JFrame.

public  void Start1(){       

    if (number==0){

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    add(getContentPane());

    //Display the window.
    pack();
    setVisible(true); 
    setExtendedState(JFrame.MAXIMIZED_BOTH); 

    setVisible(true);
}
    else {
      add(getContentPane());

    //Display the window.
        pack();  
    }
}

As discussed in the comments, the problem you're facing with updating the contents of your ContentPane a simple removeAll(); and then repaint(); would be enought. A Content Pane is always created with it's JFrame, and should not be removed if you have other options. In your case, you should only update your Content Pane's components. This is a solution I made up when I faced a similar problem:

I had a JPanel created in my Content Pane:

JPanel viewport = new JPanel();
viewport.setBackground(Color.WHITE);
viewport.setBounds(0, 302, 414, 420);
contentPane.add(viewport);
viewport.setLayout(null);

And then, whenever I wanted to update that screen, I added the following code to the method/event:

viewport.removeAll();
viewport.repaint();

This will remove every component you had and repaint it to your JPanel. So if you update the information (or whatever it is you want to update) and then run these two simple methods, you'll have your components properly updated.

If you have any other doubts, feel to check the class in which I implemented this solution in my GitHub.

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