-1

How do I have a JComboBox with a label viewable to the end user that applies a different value/data type behind the scenes?

I've built a basic calculator for my workplace. It calculates finished roll size and diameter based on length, material thickness, and core size. If I use all text fields and stick to int/double data types it's easy and works well. However dealing with sales people etc., that do not know material thicknesses, I want to switch to a combo box for those entries.

For example I want the first combo box item to say "Thermal transfer Permanent" but I want the thickness value of .005 to be entered into my math behind the scenes, and my second item would be "Thermal Direct Permanent" but I want .006 to be entered into my math. There are many more materials and thicknesses that will be added.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
KG485
  • 3
  • 2
  • As mentioned elsewhere, define a class that encapsulates the information related to these combo. entries & use those objects as a basis for the combo. Then see [How to Use Combo Boxes: Providing a Custom Renderer](https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer) for making them pretty. Here is [an example using font families](https://stackoverflow.com/questions/6965038/getting-fonts-sizes-bold-etc/6965149#6965149) (it probably should have used `Font` objects rather than `String` objects of the `Font` family name, though). – Andrew Thompson Mar 18 '18 at 00:47

1 Answers1

0

JComboBox can display list of any objects. The text it displays is (usually) text returned by the toString() method of said objects. All you need to do is to create your own data object that holds the label and the value.

Like this:

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

Then initialize your JComboBox with this data class as type parameter, like this.

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

You can access the selected item with

cb.getSelectedItem();

it will return an Object so you will have to cast it into your CoBoItem.

MatheM
  • 801
  • 7
  • 17