Button for closing a JDialog

后端 未结 5 885
[愿得一人]
[愿得一人] 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 18:45

    In addition to other answers, you can set it as the default button for the dialog root pane:

    JButton myButton = new JButton("Close");
    myButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dispose(); // Or whatever else
            setVisible(false);
        }
    });
    getRootPane().setDefaultButton(myButton);
    

    That way, its ActionListener will be called whenever Enter is pressed.

提交回复
热议问题