没有功能的 JButton

JButton without function

我遇到了按钮无法使用的问题。我以前使用过 JButtons,之前没有遇到过问题。在视觉上,该程序看起来符合预期。

谁能告诉我为什么按钮不起作用? class 使用 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");
        }
    });
}

正如 Roddy of the Frozen Peas 已经指出的,您应该做的最后一件事是使对话框可见。

这里的问题是这两行:

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

如果对话框是模态的,那么 setVisible 将阻塞,直到对话框不再可见或被释放。

这意味着setVisible之后的所有内容都是在用户点击红色X关闭window之后执行的。但此时对话框不再可见,您不再显示该对话框。