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.
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 youractionPerformed, write a factory method returning the correct implementation - it will be basically a "switch" returning the correct instance ofTask. Then you can just run this task...Taskmight look like this:On of the implementations might look like this:
Your factory will look like this:
The advantage of this is that the logic of each task is nicely encapsulated in its own class.