简体   繁体   English

如何从ActionEvent获取所有JButton组件的源代码?

[英]How to get the source of all JButton components from an ActionEvent?

I'm trying to implement a simple window that contain two buttons Yes and No . 我正在尝试实现一个包含两个按钮YesNo的简单窗口。

When clicking on Yes I want to disable the No button and when pressing on No I want to disable the Yes button. 单击Yes我想禁用No按钮,当按No我想禁用Yes按钮。

I've implemented: 我实施了:

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

...the same for the No button... ...... No按钮......

Now I'm catching the event in this method: 现在我正在用这个方法捕捉事件:

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...
    }

}

In the above method I have an access to the button that caused the event, but not to the other button. 在上面的方法中,我可以访问导致事件的按钮,但不能访问其他按钮。

What is the best way of getting the buttons? 获取按钮的最佳方法是什么?

You should just implement ActionListener as a nested class of your Dialog's class, in this case you will have full access to all fields of outer class (in which you should store reference to buttons when your create them). 您应该只将ActionListener实现为Dialog类的嵌套类,在这种情况下,您将拥有对外部类的所有字段的完全访问权限(在创建它们时应该存储对按钮的引用)。

The bad dirty solution (that should NOT be used) still exists: to navigate to battens through getParent() of JButton and then through getChildren() of parents childrens. 坏的解决方案(不应该使用)仍然存在:通过JButton的getParent()导航到battens,然后通过parent children的getChildren()导航。 Just to show that it is possible anyway. 只是为了证明它无论如何都是可能的。

You could use a JButton array as class member variable and to check which instance didnt cause the event: 你可以使用一个JButton数组作为类的成员变量,并检查其实例didnt导致事件:

for (JButton button: buttonArray) {
   if (button != source) {
      button.setEnabled(false); // disable the other button
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM