Search code examples
javaswingobjectmethodsjcombobox

Newbie question: how to access a created JComboBox instance from another method in the same class or else


If I have:

Class A {

    // bunch of stuff here

    public void intitialize() {
    // bunch of stuff here

    JComboBox jBox = new JComboBox()

    formatBox.addItem(//some objects added here))
    //I do the rest of my business in this intitialize method

    } 

}

if I want to add another method that when called can operate on jBox how can i do it? this code does not work:

Class A {

             // bunch of stuff here
             public void intitialize() {
             // bunch of stuff here
             JComboBox jBox = new JComboBox()
             formatBox.addItem(//some objects added here))
             //I do the rest of my business in this intitialize method
             }

            //newly added method
            public void anotherMethod(){

            jBox.removeItem(//some item here)

            }

}

What are the correct ways of writing this that allow jBox to be accessed from different methods of the class or other classes? and why doesn't it work this way ?


Solution

  • Use an instance variable and store the JComboBox there instead. If you want to access it from another class, you should probably create a public getJBox() method, that way the instance method can be private.

    For example:

    Class A {
    
        private JComboBox jBox;
    
        public void intitialize() {
            jBox = new JComboBox()
    
            formatBox.addItem(//some objects added here))
            //I do the rest of my business in this intitialize method
    
        }
    
        public JComboBox() getJBox() {
            return jBox;
        }
    
    }