繁体   English   中英

JComboBox设置标签和值

[英]JComboBox setting label and value

是否可以为JComboBox设置值和标签,以便我可以显示标签,但获得的值是不同的?

例如在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风险),而是使用默认的ListCellRenderer (无论可能是什么),而是将您自己的字符串作为标签文本而不是文本文本交换由值对象中的toString()定义。

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

}

正如您所看到的, ToStringListCellRendererToString实现中获取自定义字符串,然后将其传递给原始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)));

除了使用它来制作自定义标签之外,如果您创建一个基于系统区域设置创建字符串的ToString实现,您可以轻松地将组合框国际化,而无需更改值对象中的任何内容。

拜托,能给我看一个完整的例子吗?

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来实现您想要的效果。 创建一个扩展JLabel并实现ListCellRenderer 使用setRenderer()方法将该类设置为JComboBox的渲染器。 现在,当您从jcombobox访问值时,它将是jlabel类型。

步骤1创建一个具有JComboBox的两个属性的类,例如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在表单的设计中,右键单击JComboBox并选择Properties,现在打开代码选项卡并在属性Type Parameters中写入类的名称,在我们的示例中它是Product。

在此输入图像描述

步骤3现在创建一个方法,使用查询连接数据库以生成产品列表,此方法接收JComboBox对象作为参数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM