Question:
Question about a line of Java code and passing arguments?
Padawan
2009-06-12 12:27:38 UTC
Hi, I need some help with the following code. I'm having a hard time understanding what is being passed as an argument in this example:

commonButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("JButton clicked");
}});

Please help me understand what this chunk of code is doing. It looks like ActionListener() is being passed as the argument to the addActionListener method, but I'm not clear on how/why we also pass what looks like a complete method as well, and why this wouldn't be separated somewhere else.

Hope this makes sense. I'm still learning and have a long way to go, and I'll appreciate the help. Thanks
Three answers:
?
2009-06-12 12:36:58 UTC
Its basically wiring up an event handler to fire off the actionPerformed method when the commonButton is clicked and is setting a label to say its been clicked (I think!:).



Hope this helps.



Its basically just the same as a built in event handler but you're manually adding one yourself, so there's a little more legwork to do\things to wire up but don't be put off by it, altho it looks complicated its really not :)



Hope this helps
Silent
2009-06-12 19:47:18 UTC
When you do something like:



new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setText("JButton clicked");

}}



you're creating what's called an anonymous inner class. This is a shortcut way of creating a class to implement some interface (or extend some abstract class) when you only need it once and don't want to go the trouble of creating a full class in another file. When you do this, it's necessary to provide an implementation of all of the superclass's abstract methods. In this case, ActionListener has only one method to implement: actionPerformed().



The "new" operator then instantiates an object of this anonymous class by calling the default no-argument constructor that every class has. The resulting object is passed to addActionListener() as an argument.
Jack
2009-06-12 19:34:37 UTC
Firstly, this:



new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setText("JButton clicked");

}}



Is all an argument to the function commonButton.addActionListener()



This:



ActionEvent e



Is an argument to actionPerformed()



I don't speak Java, just know the general syntax; I can only verify that what you think here does seem to be correct.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...