【问题标题】:Adding arraylist object to combobox [duplicate]将arraylist对象添加到组合框[重复]
【发布时间】:2016-10-31 01:15:44
【问题描述】:

我使用 Netbeans 拖放创建了一个 JCombobox

我有一个ArrayList<Person>

如何自动将PersonFirstName 添加到组合框中。

Netbeans 生成的代码无法在 Source 视图中编辑。

【问题讨论】:

  • 只使用一个窗口监听器。在窗口打开事件中,使用每个 Person.FirstName 填充组合框。
  • 但在窗口打开后会填充数组列表

标签: java netbeans


【解决方案1】:

第 1 步:假设您有以下 Person 类。

Person.java

public class Person {

    private int id;

    private String firstName;

    private String lastName;

    public Person() {       
    }

    public Person(int id, String firstName, String lastName) {      
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;       
    }   

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return firstName;
    } 

}

第二步:创建JComboBox的实例并设置模型。

java.util.List<Person> list=new java.util.ArrayList<Person>();

list.add(new Person(1, "Sanjeev", "Saha"));
list.add(new Person(2, "Ben", "Yap"));

JComboBox<Person> comboBox = new JComboBox<Person>();
comboBox.setModel(new DefaultComboBoxModel<Person>(list.toArray(new Person[0])));

第 3 步:运行您的程序。

【讨论】:

  • 我觉得你也可以这样做:JComboBox&lt;Person&gt; comboBox = new JComboBox&lt;Person&gt;(list.toArray(new Person[0]));,拒绝第二行:comboBox.setModel(new DefaultComboBoxModel&lt;Person&gt;(list.toArray(new Person[0])));
【解决方案2】:
    public class PersonBox{
       List<Person> person= new ArrayList<Person>();
       JCombobox box; //=new JCombobox(...) ?

       //used to add a new Person to the box
       public void addPerson(Person person){
           person.add(person);
           /*
            *gets the lass element in the list and adds the first 
            *name of this specific element into the box
            */
           box.addItem(person.get(person.size()-1).getFirstName());
       }
    }

    public class Person{
       String firstName,sureName;

       public Person(String firstName, String sureName){
           this.firstName = firstName;
           this.sureName = sureName;
       }

       public String getFirstName(){
           return this.firstName;
       }

       public String getSureName(){
           return this.sureName;
       }
    }

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 2012-12-20
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多