简体   繁体   中英

How to access a variable defined in a Listener from the main class?

I have a problem with a variable in MyFrame class. I want to have in MyFrame class the value of a variable that is defined in a combobox listener.

This is my situation: I have a combobox with some friends' name. I have put a listener to the combobox which has to return the surname of the selected friend. I want to insert the value of surname in a command in MyFrame class, but there are some problems: once setted surname as final (because it has to be used in the Listener), I have an error that say:

The final local variable surname cannot be assigned, since it is defined in an enclosing type .

What is (or are) the matter(s)? Here I post my code:

public class MyFrame extends {
public static void main (String[] args)
    {
        //other 
        String [] names = {"john","al","jack"};
        final String surname=null;
        JLabel nameLbl = new JLabel("surname: " + surname);         
        JComboBox box = new JComboBox(names);    
        JPanel centralPnl = new JPanel();
        centralPnl.add(nameLbl);
        centralPnl.add(box);            
        box.addItemListener(new ItemListener()
        {
            @Override
            public void itemStateChanged(ItemEvent e) {                 
                if (e.getStateChange() == ItemEvent.SELECTED)
                { 
            // Here operations from database 
            //that return friends' surname under the variable name of "result"
                    surname = result;                       
                }
            }
        });
    }
}

You are trying to reassign a final variable, and thats the problem. Also your final variable needs to be initialised in the first place.

There are two things first one is that final variable must be initialized when it is declared and that final variable cannot be reassigned a value.

Unfortunately you are doing both of the mistakes.

Another problem is that you should post a Valid code; it will make others finding problems easily.

Beyond the issues with the code already pointed out, I guess the question is do you need to store surname or are you just using it to update the label?

If you need to store the data, move your surname variable to the class level.

If you are simply updating the label, then do something like

nameLbl.setText("surname: " + result);

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