Question

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.

Was it helpful?

Solution

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:

  • create an instance of the ActionListener
  • pass that instance to the LoginFrame constructor
  • assign the created frame to 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, i.e.

final LoginFrame login = new LoginFrame();
login.addActionListener( new ActionListener() { ... } );

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top