JComboBox设置标签和值

发布于 2024-11-01 23:29:11 字数 294 浏览 1 评论 0原文

是否可以为 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

Is it possible to set a value and a label to a JComboBox so I can show a label but get a value that is different?

For example in JavaScript I can do:

document.getElementById("myselect").options[0].value //accesses value attribute of 1st option
document.getElementById("myselect").options[0].text //accesses text of 1st option

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

深府石板幽径 2024-11-08 23:29:11

您可以将任何对象放入 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;
    }
}

You can put any object inside of a JComboBox. By default, it uses the toString method of the object to display a label navigate in the combo box using the keyboard. So, the best way is probably to define and use appropriate objects inside the combo :

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;
    }
}
握住我的手 2024-11-08 23:29:11

这是一个实用程序接口和类,可以轻松获得组合框以使用不同的标签。它不会创建替换的 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 实现,您还可以轻松国际化组合框无需更改值对象中的任何内容。

Here's a utility interface and class that make it easy to get a combo box to use different labels. Instead of creating a replacement ListCellRenderer (and risking it looking out of place if the look-and-feel is changed), this uses the default ListCellRenderer (whatever that may be), but swapping in your own strings as label text instead of the ones defined by toString() in your value objects.

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

}

As you can see the ToStringListCellRenderer gets a custom string from the ToString implementation, and then passes it to the original ListCellRenderer instead of passing in the value object itself.

To use this code, do something like the following:

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

As well as using this to make custom labels, if you make a ToString implementation that creates strings based on the system Locale, you can easily internationalize the combo box without having to change anything in your value objects.

故事灯 2024-11-08 23:29:11

请问可以给我看一个完整的例子吗?

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

Please, can show me a full example?

Instances of Enum are particularly convenient for this, as toString() "returns the name of this enum constant, as contained in the declaration."

enter image description here

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();
            }
        });
    }
}
私藏温柔 2024-11-08 23:29:11

使用 ListCellRenderer 来实现你想要的。创建一个扩展 JLabel 并实现 ListCellRenderer 的类。使用 setRenderer() 方法将该类设置为 JComboBox 中的渲染器。现在,当您从 jcombobox 访问值时,它将是 jlabel 类型。

Use ListCellRenderer to achieve what you want. Make a class that extends JLabel and implements ListCellRenderer. Set that class as a renderer in your JComboBox using setRenderer() method. Now when you access values from your jcombobox it will be of type jlabel.

凉墨 2024-11-08 23:29:11

第 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并选择“属性”,现在打开“代码”选项卡,在属性“类型参数”中写入类的名称,在我们的示例中为“产品”。

输入图片此处描述

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

Step 1
Create a class with the two properties of the JComboBox, id, name for example

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

}

Step 2
In the design of the form, right click in the JComboBox and select Properties, now open the code tab and in the property Type Parameters write the name of the class, in our example it is Product.

enter image description here

Step 3
Now create a method that connects to the database with a query to generate a list of products, this method receives as a parameter a JComboBox object.

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

}

Step 4
You can call the method from the form

public frm_products() {
    initComponents();

    Product product = new Product(); 

    product.showProducts(this.cbo_product);

}

Now you can access the selected id using getItemAt method

System.out.println(cbo_product.getItemAt(this.cbo_product.getSelectedIndex()).getId());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文