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

437 Views Asked by At

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
}
2

There are 2 best solutions below

4
bhavna garg On BEST ANSWER

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;
    }
1
Tehmina On

In order to get the selected value from a JList, one should follow these steps:

  • Create a class that extends JFrame and implements ActionListener interface.
  • Create an array of objects. These will be the values of the JList.
  • Create a new JList with the above array.
  • Create a new JButton. Add an ActionListener to the button and override the actionPerformed method. Now every time the user presses the button this method will fire up.
  • Call getSelectedIndex to get the index of the selected item in the JList.
  • Call getSelectedValue method to get the value of the selected item in the JList.