I am a student learning how to use JavaFX and I've got my first GUI working by using SceneBuilder and a Controller class. However, from my point of view the structure of the code in the controller looks incredibly messy and ugly because I put every event handler in the initialize() method of Controller. This makes it look like this:
@FXML
private void initialize() {
dealtHandLabel.setText("Your cards will be shown here.");
TextInputDialog userInput = new TextInputDialog();
userInput.setTitle("How many cards?");
userInput.setHeaderText("Enter how many cards you want to get.");
userInput.setContentText("No. of cards:");
//This makes it so that the button displays a hand of cards (of specified amount) when clicked
dealHand.setOnAction(event -> {
Optional<String> result = userInput.showAndWait();
if(result.isPresent()) {
int requestedAmount = Integer.parseInt(result.get());
StringBuilder sb = new StringBuilder();
cardHand = deck.dealHand(requestedAmount);
cardHand.forEach((card) -> sb.append(card.getAsString()).append(" "));
dealtHandLabel.setText(sb.toString());
}
});
//This button uses lambdas and streams to display requested information (sum, heart cards, etc.)
checkHand.setOnAction(event -> {
int cardSum = cardHand.stream().mapToInt(card -> card.getFace()).sum();
List<PlayingCard> spadeCards = cardHand.stream().filter((card) -> card.getSuit() == 'S').toList();
List<PlayingCard> heartCards = cardHand.stream().filter((card) -> card.getSuit() == 'H').toList();
List<PlayingCard> diamondCards = cardHand.stream().filter((card) -> card.getSuit() == 'D').toList();
List<PlayingCard> clubCards = cardHand.stream().filter((card) -> card.getSuit() == 'C').toList();
StringBuilder sb = new StringBuilder();
heartCards.forEach((card) -> sb.append(card.getAsString()).append(" "));
sumOfFacesField.setText(String.valueOf(cardSum));
heartCardsField.setText(sb.toString());
if(heartCards.size() >= 5 || diamondCards.size() >= 5 || spadeCards.size() >= 5 || clubCards.size() >= 5) {
flushField.setText("Yes");
}
else {
flushField.setText("No");
}
if(cardHand.stream().anyMatch((card) -> card.getAsString().equals("S12"))) {
spadesQueenField.setText("Yes");
}
else {
spadesQueenField.setText("No");
}
});
}
My lecturer does the exact same thing where he straight up puts every node handler into the initialize method, but I am not sure if this is good coding practice because it makes code harder to read from my point of view. Would it be better to put the different handlers into separate methods and connect them to the correct nodes using SceneBuilder, or is putting everything into initialize considered common coding practice among JavaFX developers?