ActionListeners 在模态 JDialog 中不起作用

ActionListeners don't work in modal JDialog

我为模态对话框编写了自己的 class,但是当我从我的代码中调用它时,单击按钮没有任何反应。 如果我定义 setModal(false) 一切正常。 我想并发有一些问题,但我不确定。 我的错误在哪里?

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
}
}

我用我的代码调用对话框是这样的:

PauseTaskDialog dialog = new PauseTaskDialog(taskID);

来自docs

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

尝试在 setVisible 之前调用 setModal(true)

setModal 已弃用,您应该调用 setModalityType(您需要的类型可能是 APPLICATION_MODAL),检查此 tutorial。 它与 JButton 监听器不工作无关,如果你可以点击 JButton 那么这意味着你是 运行 他们的监听器(如果有的话),如果你不能点击他们(JButton 有动画显示他们是被点击)则hidden/not在前面,与并发无关。