JComboBox设置标签和值 [英] JComboBox setting label and value

查看:241
本文介绍了JComboBox设置标签和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如在JavaScript中,我可以这样做:

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


推荐答案

您可以将任何对象放在JComboBox中。默认情况下,它使用对象的toString方法在组合框中使用键盘显示标签导航。因此,最好的方法是在组合中定义和使用适当的对象:

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

这篇关于JComboBox设置标签和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆