JComboBox设置标签和值

| 是否可以将值和标签设置为“ 0”,以便我可以显示标签但得到的值不同? 例如,在JavaScript中,我可以执行以下操作:
document.getElementById(\"myselect\").options[0].value //accesses value attribute of 1st option
document.getElementById(\"myselect\").options[0].text //accesses text of 1st option
    
已邀请:
您可以将任何对象放入JComboBox内。默认情况下,它使用对象的toString方法在键盘上的组合框中显示标签导航。因此,最好的方法可能是在组合中定义和使用适当的对象:
public class ComboItem {
    private String value;
    private String label;

    public ComboItem(String value, String label) {
        this.value = value;
        this.label = label;
    }

    public String getValue() {
        return this.value;
    }

    public String getLabel() {
        return this.label;
    }

    @Override
    public String toString() {
        return label;
    }
}
    
这是一个实用程序接口和类,可让您轻松获得组合框以使用不同的标签。而不是创建替换字符串
ListCellRenderer
(如果更改了外观,可能冒着看起来不适当的风险),而是使用默认的字符串
ListCellRenderer
(无论如何),而是将您自己的字符串替换为标签文本,而不是标签文本在值对象中由“ 5”定义。
public interface ToString {
    public String toString(Object object);
}

public final class ToStringListCellRenderer implements ListCellRenderer {
    private final ListCellRenderer originalRenderer;
    private final ToString toString;

    public ToStringListCellRenderer(final ListCellRenderer originalRenderer,
            final ToString toString) {
        this.originalRenderer = originalRenderer;
        this.toString = toString;
    }

    public Component getListCellRendererComponent(final JList list,
            final Object value, final int index, final boolean isSelected,
            final boolean cellHasFocus) {
        return originalRenderer.getListCellRendererComponent(list,
            toString.toString(value), index, isSelected, cellHasFocus);
    }

}
如您所见,
ToStringListCellRenderer
ToString
实现中获取自定义字符串,然后将其传递给原始的
ListCellRenderer
,而不是传入值对象本身。 要使用此代码,请执行以下操作:
// Create your combo box as normal, passing in the array of values.
final JComboBox combo = new JComboBox(values);
final ToString toString = new ToString() {
    public String toString(final Object object) {
        final YourValue value = (YourValue) object;
        // Of course you\'d make your own label text below.
        return \"custom label text \" + value.toString();
    }
};
combo.setRenderer(new ToStringListCellRenderer(
        combo.getRenderer(), toString)));
除了使用此方法创建自定义标签外,如果您执行基于系统区域设置创建字符串的“ 8”实现,则可以轻松地使组合框国际化,而无需更改值对象。     
  请给我看一个完整的例子吗?
Enum
的实例对此特别方便,因为
toString()
\“返回声明中包含的此枚举常量的名称。\”
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/5661556 */
public class ColorCombo extends JPanel {

    private Hue hue = Hue.values()[0];

    public ColorCombo() {
        this.setPreferredSize(new Dimension(320, 240));
        this.setBackground(hue.getColor());
        final JComboBox colorBox = new JComboBox();
        for (Hue h : Hue.values()) {
            colorBox.addItem(h);
        }
        colorBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Hue h = (Hue) colorBox.getSelectedItem();
                ColorCombo.this.setBackground(h.getColor());
            }
        });
        this.add(colorBox);
    }

    private enum Hue {

        Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow),
        Red(Color.red), Green(Color.green), Blue(Color.blue);

        private final Color color;

        private Hue(Color color) {
            this.color = color;
        }

        public Color getColor() {
            return color;
        }
    }

    private static void display() {
        JFrame f = new JFrame(\"Color\");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new ColorCombo());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }
}
    
使用ListCellRenderer实现您想要的。制作一个扩展ѭ15并实现
ListCellRenderer
的类。使用
setRenderer()
方法在您的
JComboBox
中将该类设置为渲染器。现在,当您从jcombobox访问值时,它将是jlabel类型。     
步骤1 创建一个具有两个属性class0ѭ的类,例如id,name
public class Product {
    private int id;
    private String name;


    public Product(){

    }

    public Product(int id, String name){        
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    //this method return the value to show in the JComboBox
    @Override
    public String toString(){
       return name;
    }

}
第2步 在表单的设计中,右键单击“ 0”并选择“属性”,现在打开代码选项卡,并在“类型参数”属性中输入类的名称,在我们的示例中为Product。 第三步 现在创建一个通过查询连接到数据库以生成产品列表的方法,该方法将一个“ 0”对象作为参数接收。
public void showProducts(JComboBox <Product> comboProduct){
    ResultSet res = null;
    try {
        Connection conn = new Connection();
        String query = \"select id, name from products\";
        PreparedStatement ps = conn.getConecction().prepareStatement(query);
        res = ps.executeQuery();
        while (res.next()) {
            comboProduct.addItem(new Product(res.getInt(\"id\"), res.getString(\"name\")));
        }
        res.close();
    } catch (SQLException e) {
        System.err.println(\"Error showing the products \" + e.getMessage());
    }

}
步骤4 您可以从表单中调用方法
public frm_products() {
    initComponents();

    Product product = new Product(); 

    product.showProducts(this.cbo_product);

}
现在您可以使用
getItemAt
方法访问选定的ID
System.out.println(cbo_product.getItemAt(this.cbo_product.getSelectedIndex()).getId());
    

要回复问题请先登录注册