简体   繁体   English

使用getSource对未知类型的组件执行操作

[英]Using getSource for actions on components of unknown types

I want to track specific components clicked in a specific order. 我想跟踪按特定顺序单击的特定组件。

I am using getSource and flags like this: 我正在使用getSource和像这样的标志:

public void actionPerformed(ActionEvent e) {

JButton q = (JButton)e.getSource();
JRadioButton w = (JRadioButton)e.getSource();

    if (q.equals(mybutton)) {
        if (flag == false) {
            System.out.print("test");
            flag = true;
        }
    }

This works perfectly for JButtons, the problem is using it for JRadioButtons as well. 这对于JButtons完美地起作用,问题在于也将它用于JRadioButtons。 If I use getSource on them both, click a button and it will result in an cast exception error since the button can't be cast to a Radiobutton. 如果我在两者上都使用getSource,请单击一个按钮,这将导致强制转换异常错误,因为该按钮无法强制转换为Radiobutton。

How can I work around this problem? 我该如何解决此问题?

You can use the == to compare references as the references wont change. 您可以使用==比较引用,因为引用不会更改。

if(e.getSource() == radBtn1){
 // do something
}  

I have used this in the past and it worked like a charm for me. 我过去曾经使用过它,对我来说它就像是一种魅力。

As for the class cast issue, you need to use instanceof to check to what class the source of the event belongs. 至于类强制转换问题,您需要使用instanceof检查事件源属于哪个类。 If the cause was a JButton and you cast it to JRadioButton blindly, it will result in an exception. 如果原因是JButton而您盲目地将其JRadioButtonJRadioButton ,则将导致异常。 You need this: 你需要这个:

Object source = e.getSource();
if (source instanceof JButton){
  JButton btn = (JButton) source;
} else if (source instanceof JRadioButton){
  JRadioButton btn = (JRadioButton) source;
}

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

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