带有在幕后应用不同 value/data 类型的标签的 JComboBox?

JComboBox with a label that applies a different value/data type behind the scenes?

如何让 JComboBox 具有最终用户可见的标签,并在幕后应用不同的 value/data 类型?

我为我的工作构建了一个基本计算器。它根据长度、material 厚度和芯尺寸计算成品卷的尺寸和直径。如果我使用所有文本字段并坚持使用 int/double 数据类型,这很容易并且效果很好。但是与不知道 material 厚度的销售人员等打交道,我想为这些条目切换到组合框。

例如,我希望第一个组合框项目显示 "Thermal transfer Permanent",但我希望在幕后将厚度值 .005 输入到我的数学中,而我的第二个项目将是 "Thermal Direct Permanent" 但我希望将 .006 输入到我的数学中。还有更多 materials 和厚度将被添加。

JComboBox 可以显示任何对象的列表。它显示的文本(通常)是由所述对象的 toString() 方法编辑的文本 return。您需要做的就是创建您自己的包含标签和值的数据对象。

像这样:

class CoBoItem {
    private final String display;
    private final float value;

    // constructor to create your data objects
    CoBoItem(String display, float value) {
        this.display = display;
        this.value = value;
    }
    // methods to get the values
    String getDisplay() {
        return display;
    }

    float getValue() {
        return value;
    }
    // this will be displayed in the JComboBox
    @Override
    public String toString() {
        return display;
    }
}

然后使用此数据 class 作为类型参数初始化 JComboBox,如下所示。

JComboBox<CoBoItem> cb = new JComboBox<>();
cb.addItem(new CoBoItem("Thermal transfer Permanent", 0.005f));
cb.addItem(new CoBoItem("Thermal Direct Permanent", 0.006f));

您可以通过

访问所选项目
cb.getSelectedItem();

它将 return 一个对象,因此您必须将它投射到您的 CoBoItem 中。