diff --git a/client/src/main/java/client/scenes/recipe/IngredientListCell.java b/client/src/main/java/client/scenes/recipe/IngredientListCell.java new file mode 100644 index 0000000..a5d2992 --- /dev/null +++ b/client/src/main/java/client/scenes/recipe/IngredientListCell.java @@ -0,0 +1,66 @@ +package client.scenes.recipe; + +import javafx.scene.control.ListCell; +import javafx.scene.control.TextField; + +public class IngredientListCell extends ListCell { + @Override + protected void updateItem(String item, boolean empty) { + super.updateItem(item, empty); + + if (empty || item == null) { + this.setText(null); + } else { + this.setText(item); + } + } + + @Override + public void startEdit() { + super.startEdit(); + + TextField textField = new TextField(this.getItem()); + + // Commit edit on Enter key press + textField.setOnAction(event -> { + this.commitEdit(textField.getText()); + }); + + // Cancel edit on Escape key press + textField.setOnKeyReleased(event -> { + switch (event.getCode()) { + case ESCAPE: + this.cancelEdit(); + break; + default: + break; + } + }); + + this.setText(null); + this.setGraphic(textField); + } + + private boolean isInputValid(String input) { + return input != null && !input.trim().isEmpty(); + } + + @Override + public void cancelEdit() { + super.cancelEdit(); + + this.setText(this.getItem()); + this.setGraphic(null); + } + + @Override + public void commitEdit(String newValue) { + this.setGraphic(null); + + if (!isInputValid(newValue)) { + newValue = this.getItem(); // Revert to old value if input is invalid + } + + super.commitEdit(newValue); + } +}