繁体   English   中英

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

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

我想跟踪按特定顺序单击的特定组件。

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

这对于JButtons完美地起作用,问题在于也将它用于JRadioButtons。 如果我在两者上都使用getSource,请单击一个按钮,这将导致强制转换异常错误,因为该按钮无法强制转换为Radiobutton。

我该如何解决此问题?

您可以使用==比较引用,因为引用不会更改。

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

我过去曾经使用过它,对我来说它就像是一种魅力。

至于类强制转换问题,您需要使用instanceof检查事件源属于哪个类。 如果原因是JButton而您盲目地将其JRadioButtonJRadioButton ,则将导致异常。 你需要这个:

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