Button for closing a JDialog

后端 未结 5 878
[愿得一人]
[愿得一人] 2020-12-18 17:59

I want to add a button (JButton) at the bottom of a JDialog which should close the JDialog when pressed. The problem is I don\'t know what to write in the ActionListener of

5条回答
  •  猫巷女王i
    2020-12-18 18:49

    In the actionPerformed() method of ActionListener you'll want something like:

    dialog.setVisible(false);
    

    If you want to get rid of the dialog permanently (free it from memory) then you would also call:

    dialog.dispose(); 
    

    ...where dialog is the name of your dialog. If dialog is a local variable, you'll need to make it final to access it in this way (or just make sure it's "effectively final" from Java 8 onwards).

    If you're adding the button as part of a subclass of JDialog (i.e. if you've got class MyDialog extends JDialog and you're adding the action listener in MyDialog) you'll want:

    MyDialog.this.setVisible(false);
    

提交回复
热议问题