简体   繁体   中英

How to replace one JPanel with another?

I have a class Maze (extends JPanel). I want to make a "new" button, that replace a variable of this class by new variable.

    btnNewMaze.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            maze.repaint();
            maze = new Maze((int) xSpinner.getValue(), (int) ySpinner.getValue());  
            maze.repaint();
        }
    });

Other buttons work ok. But this doesn't work correctly - doesn`t repaint, methods thorw exceptions, etc. How can I solve this or replace with another code?

Somehow I think that what you want is that a maze object which is already added to a visible container (a JPanel, for example) be substituted for a new instance of Maze when a button is pressed.

If that is the case and if this "maze" object was already added to a container (a JPanel, for example), then, when you execute the code you provided, ie: maze = new Maze(...) , your old maze object would remain added to the container and would remain unaffected. The container would still hold an inner reference to the old maze object.

In fact, when the code maze = new Maze(...) is executed, what happens isn't the former maze object substitution. Actually, what happens is that your reference variable maze is pointed to the new Maze() object, while the old instance remains attached to the container.

If what you want is the substitution of an old maze object already added to a container, then you should remove it from the container and add the new one.

This all may not be the case, but it's what I was able to understand given the provided information. Please, give us more details (a whole class or method, the exceptions that are thrown, what exactly you're trying to do, and so on).

I don't even see a JButton in the code you provided. If you want a button, you need construct it (as you would any other object), and perhaps add it to the appropriate container.

Assuming your maze instance is added to the panel, you have to remove it from the panel before replacing it with a new instance:

this.remove(maze);
maze = new Maze(....);
this.add(maze, ...);

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