0

我正在尝试实现一个包含两个按钮YesNo.

单击时Yes我想禁用No按钮,按下时No我想禁用Yes按钮。

我已经实现:

JButton btnYes = new JButton("Yes");
contentPane.add(btnYes);
btnYes.setActionCommand("Yes");
btnYes.addActionListener(this);

...No按钮也一样...

现在我正在用这种方法捕捉事件:

public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("Yes"))
    {
        //I know how to get the button that caused the event 
        //but I don't know how to disable the OTHER button.
        JButton source = (JButton)e.getSource();
        //Handle the source button...
    }

}

在上述方法中,我可以访问导致事件的按钮,但不能访问其他按钮。

获得按钮的最佳方法是什么?

4

2 回答 2

1

您应该将 ActionListener 实现为 Dialog 类的嵌套类,在这种情况下,您将可以完全访问外部类的所有字段(在创建按钮时应该在其中存储对按钮的引用)。

糟糕的肮脏解决方案(不应该使用)仍然存在:通过 JButton 的 getParent() 导航到板条,然后通过父母孩子的 getChildren() 导航到板条。只是为了表明无论如何都是可能的。

于 2012-12-29T22:21:39.363 回答
1

您可以使用JButton数组作为类成员变量并检查哪个实例没有导致事件:

for (JButton button: buttonArray) {
   if (button != source) {
      button.setEnabled(false); // disable the other button
   }
}
于 2012-12-29T22:27:45.063 回答