Search code examples
javaswingactionlistenerjcomboboxitemlistener

Best way to items in a JComboBox


I have a JComboBox with many items. I added an item listener to this combo box which stores the selected item:

    comboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            option = (String) e.getItem();
        }
    });

I have a button and when it is clicked, the program carries out the task on the basis of that selection.

Button:

public void actionPerformed(ActionEvent e) {
  if (option.toLowerCase().compareTo("contrast stretching") == 0) { /* do sth */ } 
  else if (option.toLowerCase().compareTo("mean") == 0){ /* do sth else */ }
  // And many other else if statements

The actionPerformed function is way too long. What is the best way to write the code? I don't want to make single function too long.


Solution

  • You can create an interface (e.g. Task) representing the task that needs to be executed. Then create an implementation of this interface for each of the values in the combo box (ContrastTask, MeanTask, ...). Finally, in your actionPerformed, write a factory method returning the correct implementation - it will be basically a "switch" returning the correct instance of Task. Then you can just run this task...

    Task might look like this:

    public interface Task {
      [whatever result it should return] execute([whatever parameters it needs]);
    }
    

    On of the implementations might look like this:

    public class MeanTask implements Task {
      public int execute(int a, int b) {
        return (a + b) / 2;
      }
    }
    

    Your factory will look like this:

    private Task create(String option) {
      if (option.toLowerCase().compareTo("mean") == 0) {
        return new MeanTask();
      }
      else if ....
    }
    

    The advantage of this is that the logic of each task is nicely encapsulated in its own class.