简体   繁体   English

如何为JList和DefaultListModel进行设置和获取? (JAVA)

[英]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. 我正在编写一个程序,该程序使用多个自定义jpanels实质上构成了一个jpanels This jpanels is supposed to allow the user to select a color from a Color-chooser and add or remove it from a jlist . jpanels应该允许用户从Color- jpanels中选择一种颜色,并将其从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 . 为了使将使用jpanels的窗口能够从jpanels获取数据,系统指示我为DefaultListModel和jlist进行设置和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 . 我已经看到了参数化ArrayList的setter和getter的示例,这似乎很有希望,但是我仍然不知道如何将其应用于listModel和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: 为了从JList中获取选定的值,应遵循以下步骤:

  • Create a class that extends JFrame and implements ActionListener interface. 创建一个扩展JFrame并实现ActionListener接口的类。
  • Create an array of objects. 创建一个对象数组。 These will be the values of the JList. 这些将是JList的值。
  • Create a new JList with the above array. 使用上面的数组创建一个新的JList。
  • Create a new JButton. 创建一个新的JButton。 Add an ActionListener to the button and override the actionPerformed method. 将ActionListener添加到按钮中,并覆盖actionPerformed方法。 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. 调用getSelectedIndex以获取JList中所选项目的索引。
  • Call getSelectedValue method to get the value of the selected item in the JList. 调用getSelectedValue方法以获取JList中所选项目的值。

Check this. 检查一下。 if we have a JList and a DefaultListModel 如果我们有一个JList和一个DefaultListModel

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

Now these are the getter and setter methods for the same: 现在这些是相同的getter和setter方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM