简体   繁体   中英

Disable actionListener for JComboBox (when using anonymous class)

I am using actionListener with JComboBox event . I want to disable the listener when I manually set an item selected in my program.

Here you can see this-

String item=null;
String isSetByProgram=false;

jcb1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae){
                if(isSetByProgram)
                    return;
                item=jcb1.setSelectedItem();
        }
    });

    //Now set by program
    isSetByProgram = true;
    jcb1.setSelectedItem("customItem1");
    isSetByProgram=false;

But here I am getting this:

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

How can I do this without making another separate class which extends JComboBox?

Move item and isSetByProgram to private fields of your class. Instance fields exist specifically to store state.

public class MyApplication {
    private boolean isSetByProgram;
    private String item;

    // ...

        jcb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae){
                if (isSetByProgram) {
                    return;
                }
                item = jcb1.getSelectedItem();
            }
        });

        //Now set by program
        isSetByProgram = true;
        jcb1.setSelectedItem("customItem1");
        EventQueue.invokeLater(() -> { isSetByProgram = false; });

As far as I know you can't. It is because your anonymous class works on copy of the variable which (if not final) can be changed and this is not allowed in this case.

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