破坏类的实例然后重新创建它的实例 [英] Destroy instance of class then create instance of it again

查看:103
本文介绍了破坏类的实例然后重新创建它的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个按钮,一类(级ButtonX)

i have a class (Class ButtonX) that contains a button

当用户点击这个按钮,它会创建类的实例 DialogX

when user clicks the button, it will create instance of the class DialogX

在我的班级 DialogX 它会显示的创建实例的JDialog

when I create instance of the class DialogX it will show up 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();
    }
}

那听者的JButton

    public class ListenerX {
    public static ActionListener listen = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            DialogX dialogx = null;
            dialogx = new DialogX();
        }};
}

这包含类的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);
    }

}

我怎么努力实现的是,当用户点击这个按钮,它会破坏类的实例 DialogX (如果存在),然后创建<$再次实例C $ C> DialogX

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

该怎么办?

感谢..

原谅我的英语..

推荐答案

您不能明确地破坏Java对象。一旦没有更多的引用(想想指针)向左一个对象,它会被标记为资格被垃圾收集。因此,您的code是的几乎的罚款,因为它消除了旧参考DialogX实例,并创建一个新的。
你需要做的是要么延长的JDialog 与DialogX类(那么你可以删除的JDialog变量完全),或删除静态 keywoard中的JDialog变量之前先按g 。然后,你可以调用 dialogx.dispose()(你扩展的JDialog),或者你需要实现它调用转发给 g.dispose(自定义方法)(你没有延伸的JDialog)。

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 almost fine, 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).

这篇关于破坏类的实例然后重新创建它的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆