简体   繁体   English

如何用另一个替换一个JPanel?

[英]How to replace one JPanel with another?

I have a class Maze (extends JPanel). 我有一堂迷宫课(扩展了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. 我以某种方式认为,您想要的是当按钮被按下时,已经添加到可见容器(例如,JPanel)中的迷宫对象代替了迷宫的新实例。

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. 如果是这种情况,并且如果此“迷宫”对象已添加到容器(例如,JPanel)中,则在执行所提供的代码(即: maze = new Maze(...))时 ,您的旧迷宫对象将保持添加到容器中,并且不受影响。 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. 实际上,当执行代码maze = new Maze(...)时 ,发生的不是以前的迷宫对象替换。 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. 实际上,发生的情况是您的参考变量maze指向了新的Maze()对象,而旧的实例仍附加在容器上。

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. 您提供的代码中甚至都没有看到JButton 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: 假设您的maze实例已添加到面板中,则必须先将其从面板中删除,然后再用新实例替换它:

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

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

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