java 销毁类的实例然后再次创建它的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16359662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Destroy instance of class then create instance of it again
提问by Jason Amavisca
i have a class (Class ButtonX) that contains a button
我有一个包含按钮的类(Class ButtonX)
when user clicks the button, it will create instance of the class DialogX
当用户单击按钮时,它将创建该类的实例 DialogX
when I create instance of the class DialogX
it will show up JDialog
当我创建类的实例时,DialogX
它会出现JDialog
public class ButtonX {
public ButtonX() {
JFrame me = new JFrame();
JButton n = new JButton("show dialog");
n.addActionListener(ListenerX.listen);
me.getContentPane().add(n);
me.pack();
me.setVisible(true);
}
public static void main (String[]args){
new ButtonX();
}
}
listener of that JButton
那个听众 JButton
public class ListenerX {
public static ActionListener listen = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DialogX dialogx = null;
dialogx = new DialogX();
}};
}
class that contains JDialog
包含的类 JDialog
public class DialogX {
static JDialog g = new JDialog();
public DialogX() {
JLabel label = new JLabel("label");
g.getContentPane().setLayout(new FlowLayout());
g.getContentPane().add(label);
g.pack();
g.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
g.setVisible(true);
}
}
what I try to achieve is, that when user clicks the button, it will destroy instance of class DialogX
( if it exist ) and then create again instance of DialogX
我试图实现的是,当用户单击按钮时,它将销毁类的实例DialogX
(如果存在),然后再次创建类的实例DialogX
What to do?
该怎么办?
thanks..
谢谢..
forgive my english..
原谅我的英语..
回答by Marco
You cannot explicitly destroy objects in Java. Once there are no more references (think of pointers) to an Object left, it will be marked as eligible for being garbage collected. Your code therefore is almostfine, as it removes the old reference to the DialogX instance and creates a new one.
What you need to do is either extend JDialog
with your DialogX class (then you can delete the JDialog variable completely) or remove the static
keywoard before the JDialog variable g
. Then you can call dialogx.dispose()
(you extended JDialog) or a custom method you need to implement which forwards the call to g.dispose()
(you did not extend JDialog).
您不能在 Java 中显式销毁对象。一旦不再有对某个对象的引用(想想指针),它将被标记为有资格被垃圾收集。因此,您的代码几乎没问题,因为它删除了对 DialogX 实例的旧引用并创建了一个新引用。您需要做的是扩展JDialog
您的 DialogX 类(然后您可以完全删除 JDialog 变量)或删除static
JDialog 变量之前的关键字g
。然后您可以调用dialogx.dispose()
(您扩展 JDialog)或您需要实现的自定义方法,该方法将调用转发到g.dispose()
(您没有扩展 JDialog)。