2017-06-13 50 views
0

我为模态对话框编写了自己的类,但是当我从代码中调用它时,没有任何按钮点击的反应。 如果我定义setModal(false)一切都很好。 我想有一些并发的麻烦,但我不确定。 我的错误在哪里?ActionListeners不能在模态JDialog中工作

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); 
+0

添加您的java版本 –

+0

@AdeelAhmed,1.8.0_131 – whyiamhere

+0

为了更好地为您提供帮助,请发布[MCVE]或[简短自包含正确示例](http://www.sscce.org/)。 –

回答

1

docs

注:更改可见的对话框的方式可能没有效果,直到它被隐藏然后再显示。

尝试在setVisible之前拨打setModal(true)

setModal已过时,你应该叫setModalityType,而不是(你所需要的类型可能APPLICATION_MODAL),检查此tutorial。 它与JButton监听器无法正常工作无关,如果你可以点击JButton,那么它意味着你正在运行他们的监听器(如果有的话),如果你不能点击它们(JButton有动画显示它们被点击)那么它们隐藏/不在前面,它与并发无关。

+0

问题是,按钮点击动画是运行,但此按钮的操作不是。 ActionListeners中的代码不会启动。我能够执行的这个对话框中唯一的动作是点击窗口上的Close(X)按钮。当我删除模式一切工作正常。 – whyiamhere

+0

['setModel'](https://docs.oracle.com/javase/8/docs/api/java/awt/Dialog.html#setModal-boolean-)被标记为已弃用,'modilityType'仅提供更多灵活的控制 - 只是说;) – MadProgrammer

+0

字面上五分钟前它打我,我明白你的意思。你的意思是在**(不是简单地在某处之前)'setVisible()'行之前粘贴'setModal()'**行。我很抱歉误会,英文不是我的母语。祝你有美好的一天:D – whyiamhere