简体   繁体   中英

ActionListeners don't work in modal JDialog

I wrote my own class for modal dialog, but when I call it from my code there is no any reaction on buttons clicking. If I define setModal(false) everything works great. I suppose there is some troubles with concurrency, but I'm not sure about it. Where is my mistake?

public class PauseTaskDialog extends JDialog {

private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JCheckBox prioritisingCheckBox;
private JCheckBox simultaneousWorkCheckBox;
private JCheckBox problemsWithDataCheckBox;
private JTextArea comment;

private String taskID;

public PauseTaskDialog(String task) {

    this.setContentPane(contentPane);
    this.setModal(true);
    this.setLocationRelativeTo(null);
    this.pack();

    this.setTitle("Task pause reasons");

    this.taskID = task;

    comment.setFont(comment.getFont().deriveFont(14f));
    comment.setLineWrap(true);
    comment.setWrapStyleWord(true);

    buttonOK.addActionListener(e -> {
        onOK();
    });

    buttonCancel.addActionListener(e -> {
        onCancel();
    });

    this.setVisible(true);
}


private void onOK() {
    // some code here        
}

private void onCancel() {
    // some code there
}
}

I call the dialog from my code this way:

PauseTaskDialog dialog = new PauseTaskDialog(taskID);

From the docs :

Note: changing modality of the visible dialog may have no effect until it is hidden and then shown again.

Try calling setModal(true) before setVisible .

But setModal is deprecated, you should call setModalityType instead (the type you need is likely APPLICATION_MODAL ), check this tutorial . it has nothing to do with JButton listeners not working, if you can CLICK on JButton then it means you are running their listeners(if there are any),if you cant click them(JButton has animation that shows that they are being clicked) then they are hidden/not on front, it has nothing to do with concurrency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM