Search code examples
javamodal-dialogjbuttonactionlistenerjdialog

JButton without function


I got the problem that my buttons are not working. I have used JButtons before and hadn't had a problem with them before. Visually, the program looks as intended.

Can someone tell me why the button is not working? The class uses JDialog.

JButton cancel;

public CodeExample() {
    setLayout(new FlowLayout(FlowLayout.RIGHT));
    add(cancel = new JButton ("Cancel"));
    setAlwaysOnTop(true);
    setModal(true);
    setVisible(true);


    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("test");
        }
    });
}

Solution

  • As Roddy of the Frozen Peas already pointed out, the last thing you should do is to make the dialog visible.

    The problem here are those two lines:

    this.setModal(true);
    this.setVisible(true);
    

    If a dialog is modal, then setVisible will block until the dialog is not longer visible or disposed.

    This means that everything after setVisible is executed after the user clicks on the red X to close the window. But at this point the dialog is not longer visible and you don't show the dialog again.