将arraylist对象添加到组合框

时间:2016-06-28 15:48:42

标签: java netbeans

我使用Netbeans拖放创建了JCombobox

我有ArrayList<Person>

如何自动将FirstName的{​​{1}}添加到组合框中。

Netbeans生成的代码无法在源视图中进行编辑。

2 个答案:

答案 0 :(得分: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;
    } 

}

步骤2:创建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步:运行程序。

enter image description here

答案 1 :(得分:0)

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