Add reusable autocomplete, tag chips, and dismissible toolbars

This commit is contained in:
2026-11-22 13:03:53 +01:00
parent f8ab7fc1d7
commit 32f8d28159
7 changed files with 290 additions and 3 deletions
@@ -0,0 +1,99 @@
package de.neitzel.fx.control;
import java.util.Locale;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.stage.Popup;
/** A free-form field offering case-insensitive prefix matches from an observable list. */
public final class AutoCompleteTextField extends TextField {
private static final int ROW_HEIGHT = 26;
private final ObservableList<String> suggestions = FXCollections.observableArrayList();
private final ListView<String> choices = new ListView<>();
private final Popup popup = new Popup();
private boolean accepting;
public AutoCompleteTextField() {
popup.setAutoHide(true);
popup.getContent().add(choices);
choices.setFocusTraversable(false);
choices.setFixedCellSize(ROW_HEIGHT);
choices.setOnMouseClicked(event -> {
var value = choices.getSelectionModel().getSelectedItem();
if (event.getButton() == MouseButton.PRIMARY && value != null) accept(value);
});
suggestions.addListener((ListChangeListener<String>) change -> updateSuggestions());
textProperty().addListener((property, before, after) -> updateSuggestions());
sceneProperty().addListener((property, before, after) -> popup.hide());
disabledProperty().addListener((property, before, disabled) -> {
if (disabled) popup.hide();
});
addEventFilter(KeyEvent.KEY_PRESSED, this::handleKey);
}
public ObservableList<String> getSuggestions() {
return suggestions;
}
private void handleKey(KeyEvent event) {
var selection = choices.getSelectionModel();
if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) {
if (!popup.isShowing()) updateSuggestions();
if (!popup.isShowing()) return;
if (event.getCode() == KeyCode.DOWN) selection.selectNext();
else selection.selectPrevious();
choices.scrollTo(selection.getSelectedIndex());
event.consume();
} else if (popup.isShowing() && event.getCode() == KeyCode.ESCAPE) {
popup.hide();
event.consume();
} else if (popup.isShowing() && event.getCode() == KeyCode.ENTER) {
var value = selection.getSelectedItem();
popup.hide();
if (value != null) {
accept(value);
event.consume();
}
} else if (event.getCode() == KeyCode.TAB) {
popup.hide();
}
}
private void updateSuggestions() {
if (accepting || !isFocused() || isDisabled() || getScene() == null
|| getScene().getWindow() == null || !getScene().getWindow().isShowing()) return;
String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT);
var matches = prefix.isEmpty() ? java.util.List.<String>of()
: suggestions.stream().filter(value -> value != null && !value.isBlank())
.filter(value -> value.toLowerCase(Locale.ROOT).startsWith(prefix)).distinct().limit(10).toList();
choices.getItems().setAll(matches);
choices.getSelectionModel().clearSelection();
if (matches.isEmpty()) {
popup.hide();
return;
}
var bounds = localToScreen(getBoundsInLocal());
if (bounds == null) return;
choices.setPrefSize(Math.max(170, bounds.getWidth()), ROW_HEIGHT * matches.size() + 2);
if (!popup.isShowing()) popup.show(this, bounds.getMinX(), bounds.getMaxY());
}
private void accept(String value) {
accepting = true;
try {
popup.hide();
setText(value);
positionCaret(value.length());
fireEvent(new ActionEvent());
} finally {
accepting = false;
}
}
}
@@ -0,0 +1,45 @@
package de.neitzel.fx.control;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
/** A rounded tag label with an optional remove action. */
public final class TagChip extends HBox {
private final Label label = new Label();
private final Button remove = new Button("×");
private final BooleanProperty removable = new SimpleBooleanProperty(this, "removable");
public TagChip() {
getStyleClass().add("tag-chip");
getStylesheets().add(TagChip.class.getResource("tag-chip.css").toExternalForm());
setAlignment(Pos.CENTER_LEFT);
setSpacing(3);
remove.getStyleClass().add("tag-chip-remove");
remove.accessibleTextProperty().bind(Bindings.concat("Remove ", label.textProperty()));
remove.visibleProperty().bind(removable);
remove.managedProperty().bind(removable);
getChildren().addAll(label, remove);
}
public TagChip(String text) {
this();
setText(text);
}
public StringProperty textProperty() { return label.textProperty(); }
public String getText() { return label.getText(); }
public void setText(String value) { label.setText(value); }
public BooleanProperty removableProperty() { return removable; }
public boolean isRemovable() { return removable.get(); }
public void setRemovable(boolean value) { removable.set(value); }
public EventHandler<ActionEvent> getOnRemove() { return remove.getOnAction(); }
public void setOnRemove(EventHandler<ActionEvent> handler) { remove.setOnAction(handler); }
}
@@ -0,0 +1,58 @@
package de.neitzel.fx.control;
import javafx.beans.DefaultProperty;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
/** A horizontal JavaFX toolbar with an optional dismissal button at its leading edge. */
@DefaultProperty("items")
public final class ToolBarPane extends BorderPane {
private final ToolBar toolbar = new ToolBar();
private final Button dismiss = new Button("×");
private final BooleanProperty dismissible = new SimpleBooleanProperty(this, "dismissible");
private final ObjectProperty<EventHandler<ActionEvent>> onDismiss =
new SimpleObjectProperty<>(this, "onDismiss");
public ToolBarPane() {
getStyleClass().add("tool-bar-pane");
setCenter(toolbar);
dismiss.getStyleClass().add("tool-bar-dismiss");
dismiss.setAccessibleText("Close toolbar");
BorderPane.setAlignment(dismiss, Pos.CENTER_LEFT);
BorderPane.setMargin(dismiss, new Insets(0, 3, 0, 3));
dismiss.visibleProperty().bind(dismissible);
dismiss.managedProperty().bind(dismissible);
dismissible.addListener((property, old, enabled) -> setLeft(enabled ? dismiss : null));
dismiss.setOnAction(event -> {
setVisible(false);
var handler = getOnDismiss();
if (handler != null) handler.handle(event);
});
}
public ObservableList<Node> getItems() {
return toolbar.getItems();
}
public BooleanProperty dismissibleProperty() { return dismissible; }
public boolean isDismissible() { return dismissible.get(); }
public void setDismissible(boolean value) { dismissible.set(value); }
public ObjectProperty<EventHandler<ActionEvent>> onDismissProperty() { return onDismiss; }
public EventHandler<ActionEvent> getOnDismiss() { return onDismiss.get(); }
public void setOnDismiss(EventHandler<ActionEvent> value) { onDismiss.set(value); }
public String getDismissText() { return dismiss.getAccessibleText(); }
public void setDismissText(String value) { dismiss.setAccessibleText(value); }
}
@@ -0,0 +1,16 @@
.tag-chip {
-fx-background-color: derive(-fx-base, 12%);
-fx-background-radius: 14;
-fx-border-color: -fx-outer-border;
-fx-border-radius: 14;
-fx-padding: 2 8 2 8;
}
.tag-chip .tag-chip-remove {
-fx-background-color: transparent;
-fx-padding: 0 1 0 3;
}
.tag-chip .tag-chip-remove:hover,
.tag-chip .tag-chip-remove:focused {
-fx-background-color: -fx-outer-border;
-fx-background-radius: 10;
}