2016-06-28 200 views
0

我使用Netbeans拖放功能創建了JCombobox將數組列表對象添加到組合框中

我有一個ArrayList<Person>

如何自動將PersonFirstName添加到組合框中。

由Netbeans生成的代碼不能在源代碼視圖中編輯。

+0

只需使用一個窗口監聽器。在Window打開的事件中,用每個Person.FirstName填充組合框。 – Adam

+0

但在窗口打開後會填充arraylist –

回答

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