2017-03-05 41 views
-1

我有一个叫persone(人)的类,它只是一个对象persona(person)的数组列表。 我想用这个对象来填充一个JComboBox。 我已阅读过很多文章,并且我了解到我必须使用DefaultComboBoxModel(E[] items),但当然,我错过了一些东西。我犯了一些错误。我能举一个例子吗?以及如何设置或获取所选项目?JComboBox populetd与我的对象

这是我的课:

public class Persone { 

    private ArrayList<Persona> el = new ArrayList<Persona>(); 
     public Persone() { 
    } 

    public ArrayList<Persona> getEl() { 
     return el; 
    } 

    public void setEl(ArrayList<Persona> el) { 
     this.el = el; 
    } 

    public boolean delPersonaFromPersone(Persona persona) { 
     return this.el.remove(persona); 
    } 

    public boolean addPersonaToPersone(Persona persona) { 
     return this.el.add(persona); 
    } 

    public boolean substPersonaInPersone(Persona persona, Persona withPersona) { 
     if (!this.el.remove(persona)) 
      return false; 

     return this.el.add(persona); 
    } 


    @Override 
    public String toString() { 
     return "Persone [el=" + el + "]"; 
    } 
} 

回答

1

您不能添加包含一个ArrayList组合框的对象。

相反,您需要将单个的Persona对象添加到组合框。

然后您需要提供自定义渲染器来显示Persona对象。

查看Combo Box With Custom Renderer了解更多信息和示例。

+0

好吧,我不能添加ArrayList,但我可以将其转换为数组并使用它? –

+0

@FabrizioRestori,我想你可以使用ArrayList.toArray(...)方法。或者,您可以编写循环代码,将每个项目从ArrayList直接复制到组合框。 – camickr

0

我发现我的错误(一些不好的作业)。 用于JComboBox,我从ArrayList中创建了一个新的数组。 这里我的代码:

JComboBox<Persona> cbResponsabile = new JComboBox<Persona>(); 

Persona[] array = persone.getEl().toArray(new Persona[persone.getEl().size()]); 

cbResponsabile.setModel(new DefaultComboBoxModel(array)); 
contentPanel.add(cbResponsabile); 

// ..... 
// assignment 
// persona is an element of array 
cbResponsabile.setSelectedItem(persona);