1

I've created a JCombobox using Netbeans drag and drop.

I have an ArrayList<Person>.

How do I automatically add the FirstName of the Person into the combobox.

The code generated by Netbeans cant be edited in Source view.

rbento
  • 9,919
  • 3
  • 61
  • 61
Ben Yap
  • 199
  • 1
  • 4
  • 11

2 Answers2

2

Step 1: Lets say you have the following Person class.

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

}

Step 2: Create the instance of JComboBox and set the model.

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])));

Step 3: Run your program.

enter image description here

Sanjeev Saha
  • 2,632
  • 1
  • 12
  • 19
  • I think you can also do: ```JComboBox comboBox = new JComboBox(list.toArray(new Person[0]));```, rejecting the second line: ```comboBox.setModel(new DefaultComboBoxModel(list.toArray(new Person[0]))); ``` – Biplove Lamichhane Dec 17 '20 at 04:10
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;
       }
    }
Thomas Meyer
  • 384
  • 1
  • 11