1

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?

user2079483
  • 135
  • 2
  • 3
  • 12

1 Answers1

2

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;
}
An SO User
  • 24,612
  • 35
  • 133
  • 221
  • 1
    Thanks for the answer. I have tried using instanceof but I get the error "variable [the Jbutton/Jradiobutton] might not have been initialized" from the if statements. – user2079483 Nov 24 '13 at 18:20
  • @user2079483 Where you declare your `JRadioButton`, just initialize it to `null`. Then , use the constructor somewhere to give it a value. – An SO User Nov 24 '13 at 18:21