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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top