ChawBawwa
ChawBawwa

Reputation: 43

ActionListener code explanation needed

blueButton.addActionListener(new blueButtonListner());

What happens when this code is entered?

What I think is Java compiler creates an object called blueButtonListner() and it becomes an input to (parameters for) addActionListener

If that is correct as I guessed then this code should also work:

redButton.addActionListener(rr);
redButtonListener rr =new redButtonListener();

But it shows an error. Can someone explain this to me?

Upvotes: 1

Views: 108

Answers (4)

MadProgrammer
MadProgrammer

Reputation: 347244

It's a matter if precedence, you can't have something until it's created

redButton.addActionListener(rr); redButtonListener rr =new redButtonListener();

Won't work, because rr hasn't been defined yet, the compiler has not idea of what it is.

In contrast

blueButton.addActionListener(new blueButtonListner())

The compiler creates a temporary Object and passes it to the addActionListener method.

You can correct your code with this

redButtonListener rr =new redButtonListener();
redButton.addActionListener(rr); 

Upvotes: 2

RAY
RAY

Reputation: 7100

The listener needs to be created first before it can be added. Try the following:

redButtonListener rr =new redButtonListener();
redButton.addActionListener(rr); 

Note we you get an error, usually reading carefully what the error says should give me the answer you need. In this case, it should tell you that rr is not defined, which is clearly because by the time you use it, it doesn't exist yet.

Upvotes: 1

lockstock
lockstock

Reputation: 2427

Try the code the other way around:

redButtonListener rr =new redButtonListener();

redButton.addActionListener(rr);

Upvotes: 1

pb2q
pb2q

Reputation: 59617

The listener object needs to be declared before it's used:

redButtonListener rr = new redButtonListener();
redButton.addActionListener(rr);

You're correct about blueButton.addActionListener(new blueButtonListner());. This statement creates an instance of the classblueButtonListener which is immediately passed to addActionListener.

Upvotes: 6

Related Questions