简体   繁体   中英

error: local variables referenced from an inner class must be final or effectively final

I am working with swings. This is the code I used to make a frame for logout which would return a int value and using that value other operation could be performed in the previous function. But I am getting an error. How should I solve it?

 public int logout()
{ 
int s=0;
    JFrame main=new JFrame("Logout");
    Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
main.setSize(d.width/2,d.height/3);
main.setLayout(new FlowLayout());
    JButton yes=new JButton("Yes");
main.add(yes); main.setVisible(true);   
    yes.addActionListener(new ActionListener()
{
    public void actionPerformed(java.awt.event.ActionEvent e)
    {
        s=1;
    main.setVisible(false);
    }
    });

    return s;
}

What do you expect your program to do?

The code you wrote, tries to do:

  • Create a "logout" frame with a "yes" button.
  • Return from the logout() method with the value of the s variable.
  • When later the user presses the "yes" button, you prepared an action listener to then set the s variable to 1 - but that can't work, as you already returned from the logout() method, and the variable s no longer even exists.

So, be happy that the compiler told you about a problem.

I suppose you want to wait for the user's logout approvement. Then use JOptionPane methods (the Java tutorials will help you how to do that correctly).

And by the way: get into the habit of formatting and indenting your code properly. It wasn't fun reading your code.

Use the JOptionPane class to create a confirm dialog by using one of the showConfirmDialog() method to show a confirm dialog. Please read the Java tutorial How to Make Dialogs on how to create such dialogs. The source code should look something like this:

int choice = JOptionPane.showConfirmDialog(your_main_frame,
                                           "Do you want to logout?",
                                           "Logout?",
                                           JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
    // "Yes" clicked
} else {
    // "No" clicked
}

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