【问题标题】:Store object inside JComboBox and show String attribute在 JComboBox 中存储对象并显示 String 属性
【发布时间】:2019-06-29 09:30:22
【问题描述】:

要将对象放入JComboBox,我们这样做:

while(result.next()){
    int id=rs.getInt("id");
    String name=rs.getString("name");
    Object[] itemData = new Object[] {id, name};
    jComboBox1.addItem(itemData);
}

我需要组合框只显示itemData.name 并将整个对象存储在 jcombobox 中
有合适的方法吗?

【问题讨论】:

  • 使用combo box with a custom renderer。请参阅 this answer 以获取使用字体系列名称数组的示例(它们可以很容易地成为您的 POJO 的 Font[])。从Object[] itemData .. 中创建一个 POJO

标签: java swing jcombobox


【解决方案1】:

您可以创建自己的自定义组合框。
将您想要的内容保存在那里并显示相同的内容。

例如:

public class CustomCB {
JFrame f;    
CustomCB(){    
    f=new JFrame("Custom ComboBox");    

    List<MyObj> l = new ArrayList<>();
    l.add(new MyObj("value1",1));
    l.add(new MyObj("value2",2));
    l.add(new MyObj("value3",3));

    MyCB cb=new MyCB(l); 

    for(MyObj obj: cb.l)
    {
        System.out.println(obj.s+":"+obj.i);
    }

    cb.setBounds(50, 50,90,20);    
    f.add(cb); 
    f.setLayout(null);    
    f.setSize(400,500);    
    f.setVisible(true);         
}  

class MyObj
    {
        String s;
        int i;
        MyObj(String s, int i)
        {
            this.s=s;
            this.i=i;
        }
    }

class MyCB extends JComboBox<String>
{
    List<MyObj> l;
    MyCB(List<MyObj> l)
    {
        super();
        this.l = l;
        for(MyObj obj:l)
        {
            this.addItem(obj.s);
        }
    }
} 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多