简体   繁体   中英

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:

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

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. If the cause was a JButton and you cast it to JRadioButton blindly, it will result in an exception. You need this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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