unleashed unleashed - 2 years ago 118
Java Question

JFrame removing JPanels and adding a new JPanel

I currrently have a SwingWorker that sends a HTTP Request and I override the SwingWorker's done() method to change contents in a JFrame. I want to basically remove everything and add a new members panel on the JFrame depending on the values returned from the Server.

Now, the problem I am facing is that when I invoke the following methods below on the JFrame, it doesn't remove anything from the JFrame nor does it change it's contents contained within the Frame.

//TODO: Investigate why JFrame content pane won't repaint.
//Pass the frame f reference only into MainDisplay, it doesn't actually do anything apart from allowing a class to add a JMenuBar on the JFrame.
f.add(new MainDisplay(f));

The current fix I have is this below but I would rather change the contents of the JFrame rather then loading a new one up.

f=new ApplicationFrame();

I've looked through previous answers on here and on Google and some state use validate() or invalidate() whilst calling repaint() to repaint the JFrame.

Any suggestions/help would be much appreciated.

Edit: I think I am going to debug more since there must be something else going wrong.

Answer Source

for example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyFrame extends JFrame {

    private static final long serialVersionUID = 1L;

    public MyFrame() {
        final JPanel parentPanel = new JPanel();
        parentPanel.setLayout(new BorderLayout(10, 10));

        final JPanel childPanel1 = new JPanel();
        childPanel1.setPreferredSize(new Dimension(300, 40));

        final JPanel childPanel2 = new JPanel();
        childPanel2.setPreferredSize(new Dimension(800, 600));

        JButton myButton = new JButton("Add Component ");
        myButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                parentPanel.add(childPanel2, BorderLayout.CENTER);
        setTitle("My Empty Frame");
        setLocation(10, 200);
        parentPanel.add(childPanel1, BorderLayout.CENTER);
        parentPanel.add(myButton, BorderLayout.SOUTH);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MyFrame myFrame = new MyFrame();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download