Search code examples
javaswingjlistgetter-setterdefaultlistmodel

How do I make setters and getters for JList and DefaultListModel? (Java)


I am writing a program that uses several custom jpanels to essentially make a Word-pad. This jpanelsis supposed to allow the user to select a color from a Color-chooser and add or remove it from a jlist. In order for the window that will use the jpanelsto be able to get the data from the jpanels, I was instructed to make setters and getters for my DefaultListModel and jlist. I have no idea how to do this with these types. I have seen examples of setters and getters for parameterized ArrayLists, and that seemed promising, but I still don't understand how to apply it to the listModel and jlist.

    private ArrayList<String> stringlist = new ArrayList<String>();

public ArrayList<String> getStringList() {
return stringlist;
}

public setStringList(ArrayList<String> list) {
stringlist = list
}

Solution

  • Check this. if we have a JList and a DefaultListModel

      JList listvariable= new JList();
      DefaultListModel model= new DefaultListModel<>();
    

    Now these are the getter and setter methods for the same:

       public DefaultListModel getModel() {
       return model;
        }
        public void setModel(DefaultListModel model) {
        this.model = model;
        }
    
    
    
        public JList getListvariable() {
        return listvariable;
        }
    
    
        public void setListvariable(JList listvariable) {
        this.listvariable = listvariable;
        }