I am trying to set a mouse event on mouse realeased for a button in javafx. The program is attached to an excel file which reads in the button data. When I use the event to give it a method it saying unhandled error excpetion whe I have already thrown the errors in both methods.
@FXML
void initRecipes() throws IOException, InvalidFormatException {
File file = new File("src/main/resources/RecipeList/Recipes.xlsx");
String path = file.getAbsolutePath();
ExcelReader list = new ExcelReader(path);
int i = 10;
int sheetNo = 0;
categories.add(cheap);
categories.add(showstopper);
categories.add(quick);
categories.add(breakfast);
categories.add(deserts);
categories.add(salads);
for (HBox h : categories) {
for (int k = 0; k < list.getAmount(sheetNo); k++) {
String buttonId = Integer.toString(i) + Integer.toString(k + 1);
Button button = new Button(list.getName(buttonId, sheetNo));
button.setId(buttonId);
button.setStyle("-fx-background-image: url('" +
list.getImage(buttonId, sheetNo) + "')");
button.setPrefHeight(buttonHeight);
button.setPrefWidth(buttonWidth);
button.setOnMouseReleased(event -> changeScene(buttonId));
//Error occuring here ^^^^^
h.getChildren().add(button);
}
sheetNo++;
i += 10;
}
list.close();
}
void changeScene(String buttonId) throws IOException, InvalidFormatException {
File file = new File("src/main/resources/RecipeList/ingredients.xlsx");
String path = file.getAbsolutePath();
ExcelReader list = new ExcelReader(path);
SecondaryPresenter s = new SecondaryPresenter();
s.initialize();
}
I'm quite unsure if this is the correct way to set up an event and why it is showing this error if I have already thrown the 2 errors it says I haven't handled. Does anyone know what I'm doing wrong? Thanks
The signature of EventHandler<T>.handle
is
void handle(T event)
Since your changeScene
has a throws
clause containing exceptions that are not RuntimeException
s, the java compiler determines that these kind of exceptions are not handled in your lambda expression. The lambda expression results in a very similar result as the following code:
button.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
changeScene(buttonId);
}
});
In the code above it should be easy to see that the handle
method does not handle the exceptions thrown by changeScene
properly.
You need to add a try/catch
to the body of the lambda expression:
button.setOnMouseReleased(event -> {
try {
changeScene(buttonId);
} catch (IOException | InvalidFormatException ex) {
// TODO: exception handling
}
});