I'm looking to make a single method that takes in my object and spits out a checkbox with an item listener.
Here's my relevant portion, the IDE wants me to make my argument and checkbox final prevents the listener from functioning during runtime.

Any ideas or help would be appreciated, thank you!

    public JCheckBox makeCheckBox(Jobs object) {
    JCheckBox newCheckBox = new JCheckBox(object.getName());

    newCheckBox.addItemListener(new ItemListener(){ 
        public void itemStateChanged(ItemEvent e){
            } else {
        return newCheckBox;

Recommended Answers

All 3 Replies

hai Lamirp

your code works fine for the first time.

when you call that method makeCheckBox(Jobs object) for second time it throws an error to you
because you are creating the Jcheckbox with the same reference of the Jcheckbox what you created for first time

so i think you need to change your code

let me know am i correct or not

happy coding

No, sorry radhakrishna.p, that explanation is not right.
The problem is that the parameter and the newCheckBox variable are local to the makeCheckBox method. As soon as that method finishes both those variables are discarded.
Some time later the ItemListener is called, which tries to use those variables, but they no longer exist.

If you declare them "final" then the compiler knows their value will never change. That means it can safely take a copy of those values for the ItemListener to use when it runs.

Every time you call makeCheckBox you get new versions of those two variables, and a new ItemListstener. Because these are new versions each time they can each have their own final values.

Just go ahead and declare them both final. If something is wrong at run time, it's something else, eg the "this" online 7 that refers to the ItemListener instance which will never be the source.

ps the if test on line 7 is redundant because every checkbox has its own unique listener instance.

Thank you both, made them final as James suggested removed the initial if and it worked. Thank you guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.