Issue
I have a controller class in a JavaFX program which is handling numerous Nodes. I created a method addEventListeners
which looks like:
cleanButton.setOnAction(e -> {
...
});
advSett.setOnAction(e -> {
...
});
imageLoaderItem.setOnAction(e -> {
...
});
outputButton.setOnAction(e -> {
...
});
And so on for each element handled by the controller. This method is occupying 300 lines of code making the controller class quite messy. I was wondering, is there a cleaner way of adding the listeners?
Solution
As correctly pointed out in the comments, splitting your Controller into several smaller ones is usually a good idea when you are facing such problems. Still, there are ways to avoid repetition of the same or similar instructions. If all your Buttons / Nodes do the same, you can simply do this:
private void addEventListener(final ButtonBase element) {
element.setOnAction(e -> {
//do the thing
});
}
If most of your Nodes do the same and only two or three differ, then you can expand the same method like so:
private void addEventListener(final ButtonBase element) {
if (element == cleanButton) {
element.setOnAction(e -> {
//do the thing
});
} else {
element.setOnAction(e -> {
//do the other thing
});
}
}
If you have identifyable groups of buttons that do the same, say group A doing x and group B doing y, then you can for example add them to a set each and handle them this way
private void addEventListener(final ButtonBase element) {
if (groupA.contains(element)) {
element.setOnAction(e -> {
//do the thing for A
});
} else {
element.setOnAction(e -> {
//do the other thing
});
}
}
Finally, you can also flip this on its head. If the common denominator is the event, rather than the Nodes, then you can also refactor your function to handle the event on the specific element it came from
private void handleButtonClicks(final javafx.event.ActionEvent mouseEvent) {
switch (mouseEvent.getSource()) {
case cleanButton:
// and so on
default:
}
}
Answered By - Vinz
Answer Checked By - Willingham (JavaFixing Volunteer)