I’m working on a Java Swing unit converter. The user selects a unit category from a JComboBox, and based on that selection, I update two other JComboBox<Units> with corresponding enum values (Length.values(), Weight.values(), etc.).
Currently, my method looks like this:
private void selectUnit(ActionEvent e) {
if (view.getCategoryBox().getSelectedItem().toString().equals("LENGTH")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Length.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Length.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("WEIGHT")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Weight.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Weight.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("TEMPERATURE")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Temperature.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Temperature.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("TIME")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Time.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Time.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("VOLUME")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Volume.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Volume.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("AREA")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Area.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Area.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("SPEED")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Speed.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Speed.values()));
} else if (view.getCategoryBox().getSelectedItem().toString().equals("ENERGY")) {
view.getInputBoxUnit().setModel(new DefaultComboBoxModel<>(Energy.values()));
view.getOutputBoxUnit().setModel(new DefaultComboBoxModel<>(Energy.values()));
}
}
This works, but it’s repetitive and feels hard to maintain.
Is there a cleaner or more elegant way to refactor this without using so many if/else statements?
Converterexample, cited here and here.