0

我在使用 actionListener 时遇到了麻烦。我创建了自己的简单对话框,它只有两个 JButton - 是和否。当我单击按钮时,actionListener 没有响应。

这是我的代码:

private void showInfoNewUML() {        
    Dimension buttonsSize = new Dimension(60, 25);
    Dimension programSize = new Dimension(1200, 700);
    final JDialog dialogWindow = new JDialog(this, "Erase actual UML diagram"
            + " with his files", true);        
    JTextArea descDialogWindow = new JTextArea("Do you really erase actual\n"
            + "UML diagram with his files?   ");
    descDialogWindow.setEditable(false);
    descDialogWindow.setBackground(new Color(220, 220, 220));
    descDialogWindow.setBorder(null);
    dialogWindow.getContentPane().setBackground(new Color(220, 220, 220));
    dialogWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    dialogWindow.setModal(true);
    dialogWindow.setResizable(false);
    dialogWindow.setLayout(new FlowLayout());
    dialogWindow.setSize(310, 100);
    dialogWindow.setLocation((int) programSize.getWidth() / 2,
            (int) programSize.getHeight() / 2);
    JButton buttonYes = new JButton("Yes");
    JButton buttonNo = new JButton("No");
    buttonYes.setPreferredSize(buttonsSize);
    buttonNo.setPreferredSize(buttonsSize);
    dialogWindow.add(descDialogWindow);
    dialogWindow.add(buttonYes);
    dialogWindow.add(buttonNo);
    dialogWindow.setVisible(true);

    buttonYes.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            buttonAnoActionPerformed(e);
        }

        private void buttonAnoActionPerformed(ActionEvent e) {
            dialogWindow.setVisible(false);
        }
    });

    buttonNo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            buttonNeActionPerformed(e);
        }

        private void buttonNeActionPerformed(ActionEvent e) {
            dialogWindow.setVisible(false);
        }
    });
}

单击按钮后,我想关闭此对话框。当我点击右上角的十字按钮时,对话框窗口关闭。

感谢您帮助解决这个问题。

4

1 回答 1

2

尝试在调用之前dialogWindow.setVisible(true);添加 ActionListeners 。

您的对话框是模态的,因此在对话框关闭之前showInfoNewUML会一直阻塞dialogWindow.setVisible(true);,这对于注册任何有用的侦听器来说太晚了。

于 2012-04-05T21:44:26.427 回答