JButton对actionListener没有响应

时间:2012-04-05 21:37:10

标签: java jbutton actionlistener

我在使用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);
        }
    });
}

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

感谢你帮忙解决这个问题。

1 个答案:

答案 0 :(得分:2)

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

您的对话框是模态的,因此showInfoNewUML将在dialogWindow.setVisible(true);处阻止,直到对话框关闭为止,这对于注册任何有用的侦听器来说为时已晚。