I have 14 pairs of Buttons associated with two groups of textFields that increment and decrement their associated textFields by 2. Each text field displays how many pairs of plates of specific weights are to be loaded onto a barbell. They are stored in two 2-dimensional arrays, one for pounds and the other for kilograms. [increment or decrement][buttons]
final Button[][] poundIncrementDecrementButton = new Button[2][7];
final Button[][] kilogramIncrementDecrementButton = new Button[2][7];
I'm using Scene Builder and JavaFX, and I'm trying to avoid writing 28 @FXML event handlers. This is the method I've come up with so far to iterate through each of the arrays, but I'm not sure how I can replace the lambda expressions to make this work.
// assigns event handlers to increment and decrement buttons.
private void incrementDrecimentButtonEventHandlers() {
// p=1 increment buttons, p=2 decrement buttons
for (int p = 0; p < poundIncrementDecrementButton.length; p++) {
// loops through buttons
for (int j = 0; j < poundIncrementDecrementButton[p].length; j++) {
Button incrementButton = poundIncrementDecrementButton[p][j];
final int incrementDecriment = p;
final int textField = j;
incrementButton.setOnAction((ActionEvent event) -> {
incrementDecrementPlate("pounds", incrementDecriment, textField);
});
}
// k=1 increment buttons, k=2 decrement buttons
for (int k = 0; k < kilogramIncrementDecrementButton.length; k++) {
// loops through buttons
for (int j = 0; j < kilogramIncrementDecrementButton[k].length; j++) {
Button incrementButton = kilogramIncrementDecrementButton[k][j];
final int incrementDecriment = k;
final int textField = j;
incrementButton.setOnAction((ActionEvent event) -> {
incrementDecrementPlate("kilograms", incrementDecriment, textField);
});
}
}
}
}
I then have the event handlers call this method with the relevant indices.
// increments or decrements the plates
private void incrementDecrementPlate(String unit, int incrementDecrement, int textField) {
Double oldValue = Double.parseDouble(poundTextFieldList.get(textField).getText());
String incremented;
String decremented;
if (oldValue % 2 != 0) {
incremented = Double.toString(oldValue + 1);
} else {
incremented = Double.toString(oldValue + 2);
}
if (oldValue % 2 != 0) {
decremented = Double.toString(oldValue - 1);
} else if (oldValue != 0) {
decremented = Double.toString(oldValue - 2);
} else {
decremented = Double.toString(oldValue);
}
switch (unit) {
case "pounds":
if (incrementDecrement == 0) {
poundTextFieldList.get(textField).setText(incremented);
} else {
poundTextFieldList.get(textField).setText(decremented);
}
break;
case "kilograms":
if (incrementDecrement == 0) {
kilogramTextFieldList.get(textField).setText(incremented);
} else {
kilogramTextFieldList.get(textField).setText(decremented);
}
break;
}
}