简体   繁体   中英

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?

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 class blueButtonListener which is immediately passed to addActionListener .

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); 

Try the code the other way around:

redButtonListener rr =new redButtonListener();

redButton.addActionListener(rr);

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.

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