I can't seem to find an answer to this through all the anonymous inner class questions on the site.
public void start()
{
/* Ask the user to login */
final LoginFrame login;
login = new LoginFrame(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent event)
{
switch (event.getActionCommand())
{
case "login":
/* @todo Login the user */
String username = login.getUsername();
String password = login.getPassword();
}
}
});
login.display();
}
My login frame takes in an ActionListener
. How do I access login
from within the new ActionListener()
?
Right now I'm getting an error:
Variable login may not have been initialized.
AFAIK you can't because the ActionListener
will be created first and at that time must have access to the final variable login
which isn't initialized yet.
The order of calls would be like this:
ActionListener
LoginFrame
constructor login
Now assume the ActionListener
constructor would access login
- it wouldn't be initialized yet and would cause an error.
To fix this you'd need to create the frame first and then set the ActionListener
, ie
final LoginFrame login = new LoginFrame();
login.addActionListener( new ActionListener() { ... } );
You'll have to assign the ActionListener
after the LoginFrame
has been created.
The right-hand side of the assignment is evaluated first or prior to the login
field being assigned as the compiler is telling you.
It's more common for with listeners is to have an add
method, so I'd change the code to read:
private final login = new LoginFrame();
login.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent event)
{
switch (event.getActionCommand())
{
case "login":
/* @todo Login the user */
String username = login.getUsername();
String password = login.getPassword();
}
}
}
);
login.display();
You haven't initialized your variable login
and you are using it.
By your anonymous class
, you are initializing your variable, so you can use it after initializing it. And if you want to use this variable, you have to initialize it (but never initialize your variable with null
value because you are using methods of LoginFrame
class and it must throw NullPointerException
).
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.