Destroy instance of class then create instance of

2019-07-15 03:15发布

问题:

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

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

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();
    }
}

listener of that 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

 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

What to do?

thanks..

forgive my english..

回答1:

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).