简体   繁体   中英

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 jpanels is 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 jpanels to 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
}

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.

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

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