【问题标题】:ActionListeners don't work in modal JDialogActionListeners 在模态 JDialog 中不起作用
【发布时间】:2017-06-13 09:16:15
【问题描述】:

我为模态对话框编写了自己的类,但是当我从我的代码中调用它时,按钮点击没有任何反应。 如果我定义 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);

【问题讨论】:

标签: java swing actionlistener jdialog


【解决方案1】:

来自docs:

注意:更改可见对话框的模式可能无效,直到它被隐藏然后再次显示。

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

但是setModal 已被弃用,你应该调用setModalityType 代替(你需要的类型可能是APPLICATION_MODAL),检查这个tutorial。 它与 JButton 侦听器不起作用无关,如果您可以 CLICK on JButton 则意味着您正在运行他们的侦听器(如果有的话),如果您无法点击它们(JButton 有动画显示它们正在被点击)然后它们是隐藏的/不在前面,它与并发无关。

【讨论】:

  • 问题是按钮点击动画正在运行,但该按钮的动作没有。 ActionListeners 内的代码无法启动。在此对话框中我能够执行的唯一操作是单击窗口上的关闭 (X) 按钮。当我删除模态时,一切正常。
  • setModel 被标记为已弃用,modilityType 只是提供更灵活的控制 - 只是说;)
  • 从字面上看,五分钟前它击中了我,我明白了你的意思。您的意思是将setModal() 就在 行之前(不仅仅是之前的某个位置)粘贴setVisible() 行。很抱歉造成误解,英语不是我的母语。祝你有美好的一天:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 2018-06-27
  • 2013-07-24
相关资源
最近更新 更多