Add DataGrid column visibility controls and action icons

This commit is contained in:
2026-11-23 13:05:31 +01:00
parent dcd26a088f
commit 42c1ee19a1
11 changed files with 410 additions and 50 deletions
@@ -0,0 +1,32 @@
package de.neitzel.fx.control;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.SVGPath;
/** A button graphic that follows the control's text color and exposes a tooltip and accessible name. */
public final class ActionIcon {
private ActionIcon() {}
/** Installs an outlined icon drawn on a 16 by 16 coordinate grid. */
public static void install(ButtonBase button, String description, String path) {
var icon = new SVGPath();
icon.setContent(path);
icon.setFill(null);
icon.strokeProperty().bind(button.textFillProperty());
icon.setStrokeWidth(1.5);
icon.setStrokeLineCap(javafx.scene.shape.StrokeLineCap.ROUND);
icon.setStrokeLineJoin(javafx.scene.shape.StrokeLineJoin.ROUND);
var graphic = new StackPane(icon);
graphic.setMinSize(18, 18);
graphic.setPrefSize(18, 18);
graphic.setMaxSize(18, 18);
graphic.setMouseTransparent(true);
button.setGraphic(graphic);
button.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
button.setAccessibleText(description);
button.setTooltip(new Tooltip(description));
}
}
@@ -33,8 +33,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
previous = pagingButton("Previous page", "M2 7 L14 0 V14 Z"),
next = pagingButton("Next page", "M2 0 L14 7 L2 14 Z"),
last = pagingButton("Last page", "M0 0 L12 7 L0 14 Z M14 0 H16 V14 H14 Z"),
retry = new Button("Retry"),
refresh = new Button("Refresh");
retry = actionButton("Retry", "M2 8 A6 6 0 1 1 5 13 M2 3 V8 H7"),
refresh = actionButton("Refresh", "M14 7 A6 6 0 1 0 13 11 M14 2 V7 H9");
private final ComboBox<String> pageSize = new ComboBox<>();
private GridQuery initial;
private List<ResultColumn> columnDefinitions;
@@ -59,6 +59,8 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private final Label activeFilters = new Label();
private final Label interactionStatus = new Label();
private final MenuButton setupMenu = new MenuButton("Grid setup");
private final MenuButton columnMenu = new MenuButton();
private final ReadOnlyLongWrapper columnVisibilityRevision = new ReadOnlyLongWrapper();
private final ReadOnlyLongWrapper committedRevision = new ReadOnlyLongWrapper();
private List<String> defaultGrouping = List.of();
private GridSetup developerDefaults;
@@ -68,6 +70,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
private GridPersistenceAttachment<K, T> attachment;
private GridColumnSettings<K, T> columnSettings;
private static Button actionButton(String description, String path) {
var button = new Button();
de.neitzel.fx.control.ActionIcon.install(button, description, path);
return button;
}
private static Button pagingButton(String name, String path) {
var button = new Button();
var icon = new SVGPath();
@@ -272,7 +280,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
List.of(),
new PageRequest.Paged(
0, Math.min(50, source.capabilities().maximumPageSize())));
renderer = table.openResults(columns, rowFactory);
renderer = table.openResults(columns, rowFactory, columnMenu);
columnMenu.getStyleClass().add("data-grid-column-menu");
columnMenu.setAccessibleText("Column visibility");
columnMenu.setTooltip(new Tooltip("Column visibility"));
columnMenu.setOnShowing(event -> updateColumnMenu());
renderer.setHeaderMenuFactory(this::headerMenu);
renderer.setSelectionMode(getSelectionMode());
selectedKeys.bind(renderer.selectedKeysProperty());
selectedElements.bind(renderer.selectedElementsProperty());
@@ -343,9 +356,12 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
controls.getChildren().add(setupMenu);
interactionStatus.setWrapText(true);
interactionStatus.getStyleClass().add("data-grid-interaction-status");
de.neitzel.fx.control.ActionIcon.install(setupMenu, "Grid setup",
"M2 4 H14 M2 8 H14 M2 12 H14 M5 2 V6 M11 6 V10 M7 10 V14");
var css = DataGrid.class.getResource("data-grid.css");
if (css != null) getStylesheets().add(css.toExternalForm());
Button clearActiveFilters = new Button("Clear filters");
Button clearActiveFilters = actionButton("Clear filters",
"M1 2 H15 L9 8 V14 L6 12 V8 Z M11 10 L15 14 M15 10 L11 14");
clearActiveFilters.setOnAction(e -> setFilters(List.of()));
filterSummary.getChildren().addAll(activeFilters, clearActiveFilters);
filterSummary.setVisible(false);
@@ -417,6 +433,66 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
renderer.setColumnOrder(ids);
}
/** Returns whether this grid currently displays the column. */
public boolean isColumnVisible(String id) {
check();
return renderer.isColumnVisible(id);
}
/** Shows or hides a column without fetching rows or changing the saved grid setup. */
public void setColumnVisible(String id, boolean visible) {
if (visible == isColumnVisible(id)) return;
closeFilter();
renderer.setColumnVisible(id, visible);
columnVisibilityRevision.set(columnVisibilityRevision.get() + 1);
}
/** Observes effective visibility changes, which are independent of saved grid setups. */
public ReadOnlyLongProperty columnVisibilityRevisionProperty() {
return columnVisibilityRevision.getReadOnlyProperty();
}
private void updateColumnMenu() {
columnMenu.getItems().setAll(renderer.columnOrder().stream().map(id -> {
CheckMenuItem item = new CheckMenuItem(renderer.columnHeader(id));
item.setSelected(isColumnVisible(id));
item.setOnAction(e -> setColumnVisible(id, item.isSelected()));
return item;
}).toList());
}
private ContextMenu headerMenu(String id, HBox cell) {
var menu = new ContextMenu(
menuItem("Sort ascending", () -> setSort(new SortKey(id, SortKey.Direction.ASCENDING))),
menuItem("Sort descending", () -> setSort(new SortKey(id, SortKey.Direction.DESCENDING))));
if (query().sort().stream().anyMatch(key -> key.columnId().equals(id)))
menu.getItems().add(menuItem("Clear sort", () -> setSort(null)));
if (filterColumns.containsKey(id)) {
var filterButton = cell.lookup(".filter-button");
menu.getItems().add(menuItem("Filter…", () -> openFilter(id, filterButton)));
}
if (renderer.canGroup(id)) {
boolean grouped = renderer.groupingColumns().contains(id);
menu.getItems().add(menuItem(grouped ? "Remove grouping" : "Group by column", () -> {
var nextGroups = new ArrayList<>(renderer.groupingColumns());
if (grouped) nextGroups.remove(id);
else if (!nextGroups.contains(id)) nextGroups.add(id);
setGroupingColumns(nextGroups);
}));
}
menu.getItems().addAll(
menuItem("Reset column width", () -> setColumnWidth(id, new ColumnWidth.Default())),
new SeparatorMenuItem(),
menuItem("Hide column", () -> setColumnVisible(id, false)));
return menu;
}
private static MenuItem menuItem(String text, Runnable action) {
var item = new MenuItem(text);
item.setOnAction(e -> action.run());
return item;
}
public double setColumnWidth(String id, ColumnWidth width) {
check();
closeFilter();
@@ -1252,6 +1328,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
}
if (attachment != null) attachment.close();
closed = true;
columnMenu.hide();
closeFilter();
declaration.close();
if (coordinator != null) coordinator.close();
@@ -25,6 +25,10 @@ final class ResultColumnSeparators extends Group {
return decoration;
}
boolean matchesColumnCount(int columns) {
return getChildren().size() == Math.max(0, columns - 1);
}
void position(double[] widths) {
double x = 0;
for (int i = 0; i < getChildren().size(); i++) {
@@ -343,13 +343,10 @@ final class ResultHeaderGestures implements AutoCloseable {
headerViewport = pane;
break;
}
if (scroll == null
|| headerViewport == null
|| Double.isNaN(pointerX)
|| !headerViewport
.localToScene(headerViewport.getBoundsInLocal())
.contains(pointerX, pointerY)) return;
var bounds = scroll.localToScene(scroll.getViewportBounds());
if (scroll == null || headerViewport == null || Double.isNaN(pointerX))
return;
var bounds = headerViewport.localToScene(headerViewport.getBoundsInLocal());
if (!bounds.contains(pointerX, pointerY)) return;
double delta =
pointerX < bounds.getMinX() + 30
? -.012
@@ -2,6 +2,8 @@ package de.neitzel.fx.view;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.geometry.Insets;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
@@ -9,29 +11,43 @@ import javafx.scene.layout.VBox;
/** Makes equal normalized scroll values represent equal pixel offsets in queried results. */
final class ResultScrollAlignment implements AutoCloseable {
private final HBox header;
private final VBox body;
private final double originalMinimum;
private final Insets originalPadding;
private final ObjectBinding<Insets> bodyPadding;
private final DoubleBinding minimum;
private final DoubleBinding viewportDifference;
ResultScrollAlignment(HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll) {
ResultScrollAlignment(
HBox header, VBox body, ScrollPane headerScroll, ScrollPane bodyScroll,
boolean hasHeaderAccessory) {
this.header = header;
this.body = body;
originalMinimum = header.getMinWidth();
originalPadding = body.getPadding();
viewportDifference = Bindings.createDoubleBinding(
() -> headerScroll.getViewportBounds().getWidth()
- bodyScroll.getViewportBounds().getWidth(),
headerScroll.viewportBoundsProperty(), bodyScroll.viewportBoundsProperty());
// The fixed header menu can make the header viewport narrower. Add trailing body space
// so the last column can scroll fully into view in both viewports.
bodyPadding = hasHeaderAccessory ? Bindings.createObjectBinding(
() -> new Insets(originalPadding.getTop(),
originalPadding.getRight() + Math.max(0, -viewportDifference.get()),
originalPadding.getBottom(), originalPadding.getLeft()),
viewportDifference) : null;
if (bodyPadding != null) body.paddingProperty().bind(bodyPadding);
// A vertical body scrollbar narrows its viewport. Trailing row actions can also
// make its content wider than the column headings. Reserve blank header space
// so both scrollable extents match; the existing two-way hvalue binding then
// moves every mapped field and heading by the same number of pixels.
minimum =
Bindings.createDoubleBinding(
() ->
body.getLayoutBounds().getWidth()
+ Math.max(
0,
headerScroll.getViewportBounds().getWidth()
- bodyScroll
.getViewportBounds()
.getWidth()),
body.layoutBoundsProperty(),
headerScroll.viewportBoundsProperty(),
bodyScroll.viewportBoundsProperty());
() -> body.getLayoutBounds().getWidth()
+ (hasHeaderAccessory
? viewportDifference.get()
: Math.max(0, viewportDifference.get())),
body.layoutBoundsProperty(), viewportDifference);
header.minWidthProperty().bind(minimum);
}
@@ -40,5 +56,11 @@ final class ResultScrollAlignment implements AutoCloseable {
header.minWidthProperty().unbind();
header.setMinWidth(originalMinimum);
minimum.dispose();
if (bodyPadding != null) {
body.paddingProperty().unbind();
body.setPadding(originalPadding);
bodyPadding.dispose();
}
viewportDifference.dispose();
}
}
+14 -1
View File
@@ -246,13 +246,26 @@ public class Table extends VBox {
*/
public <K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
java.util.function.Function<T, ResultRow> factory) {
return openResults(definitions, factory, null);
}
<K, T> TableResults<K, T> openResults(List<ResultColumn> definitions,
java.util.function.Function<T, ResultRow> factory, Region headerAccessory) {
if (!javafx.application.Platform.isFxApplicationThread()) {
throw new IllegalStateException("Use the JavaFX application thread");
}
if (opened || resultMode) {
throw new IllegalStateException("Table is already open");
}
TableResults<K, T> renderer = new TableResults<>(header, body, List.copyOf(definitions), factory, headerScroll, scroll);
TableResults<K, T> renderer = new TableResults<>(
header, body, List.copyOf(definitions), factory, headerScroll, scroll, headerAccessory);
if (headerAccessory != null) {
getChildren().remove(headerScroll);
headerScroll.setMinWidth(0);
HBox.setHgrow(headerScroll, Priority.ALWAYS);
headerAccessory.setMaxHeight(Double.MAX_VALUE);
getChildren().addFirst(new HBox(headerScroll, headerAccessory));
}
// DataGrid grows this Table; let its viewport consume that height as well.
VBox.setVgrow(scroll, Priority.ALWAYS);
resultMode = true;
@@ -8,8 +8,10 @@ import javafx.collections.*;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.geometry.Side;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.KeyEvent;
@@ -20,6 +22,7 @@ import javafx.scene.layout.VBox;
import javafx.scene.shape.SVGPath;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
@@ -31,10 +34,12 @@ import java.util.function.Function;
public final class TableResults<K, T> implements AutoCloseable {
private final HBox header;
private final VBox body;
private final Region headerAccessory;
private final Function<T, ResultRow> factory;
private final Map<String, ResultColumn> definitions = new LinkedHashMap<>();
private final Map<String, ColumnWidth> widths = new LinkedHashMap<>();
private List<String> order;
private final Set<String> hiddenColumns = new HashSet<>();
private List<Entry<K, T>> entries = List.of();
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
@@ -56,6 +61,8 @@ public final class TableResults<K, T> implements AutoCloseable {
private List<SortKey> sortKeys = List.of();
private java.util.function.BiConsumer<String, Node> filterRequest = (id, node) -> {};
private java.util.function.Consumer<String> sortRequest = id -> {};
private BiFunction<String, HBox, ContextMenu> headerMenuFactory;
private ContextMenu headerMenu;
private List<GroupColumn<T>> groupColumns = List.of();
private List<String> grouping = List.of();
@@ -79,10 +86,12 @@ public final class TableResults<K, T> implements AutoCloseable {
List<ResultColumn> columns,
Function<T, ResultRow> factory,
javafx.scene.control.ScrollPane headerScroll,
javafx.scene.control.ScrollPane bodyScroll) {
javafx.scene.control.ScrollPane bodyScroll,
Region headerAccessory) {
requireFx();
this.header = header;
this.body = body;
this.headerAccessory = headerAccessory;
this.factory = Objects.requireNonNull(factory);
gestures = new ResultHeaderGestures(this, header, body);
if (columns.isEmpty())
@@ -94,7 +103,8 @@ public final class TableResults<K, T> implements AutoCloseable {
}
order = List.copyOf(definitions.keySet());
validateOrder(order);
scrollAlignment = new ResultScrollAlignment(header, body, headerScroll, bodyScroll);
scrollAlignment = new ResultScrollAlignment(
header, body, headerScroll, bodyScroll, headerAccessory != null);
drawHeader();
body.setOnMouseClicked(e -> {
if (e.getTarget() == body && e.getButton() == MouseButton.PRIMARY) select(null);
@@ -105,7 +115,7 @@ public final class TableResults<K, T> implements AutoCloseable {
checkOpen();
columnSeparators = true;
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
applyWidths(widths);
}
public ReadOnlyObjectProperty<K> selectedKeyProperty() {
@@ -143,6 +153,27 @@ public final class TableResults<K, T> implements AutoCloseable {
return Map.copyOf(widths);
}
boolean isColumnVisible(String id) {
checkOpen();
if (!definitions.containsKey(id)) throw new IllegalArgumentException("Unknown column: " + id);
return !hiddenColumns.contains(id);
}
void setColumnVisible(String id, boolean visible) {
if (visible == isColumnVisible(id)) return;
Node focus = header.getScene() == null ? null : header.getScene().getFocusOwner();
boolean headerFocused = focus != null && descendant(header, focus);
if (visible) hiddenColumns.remove(id);
else hiddenColumns.add(id);
drawHeader();
applyWidths(widths);
if (headerFocused && headerAccessory != null) headerAccessory.requestFocus();
}
private List<String> visibleOrder(List<String> ordering) {
return ordering.stream().filter(id -> !hiddenColumns.contains(id)).toList();
}
/** Marks retained rows unavailable without disabling header/query controls. */
public void setRowsInteractive(boolean interactive) {
checkOpen();
@@ -157,6 +188,11 @@ public final class TableResults<K, T> implements AutoCloseable {
sortRequest = Objects.requireNonNull(handler);
}
void setHeaderMenuFactory(BiFunction<String, HBox, ContextMenu> factory) {
checkOpen();
headerMenuFactory = Objects.requireNonNull(factory);
}
/** Opt-in filter actions; clicking the icon never issues a sort request. */
public void setFilterActions(
Set<String> columns, java.util.function.BiConsumer<String, Node> handler) {
@@ -196,8 +232,12 @@ public final class TableResults<K, T> implements AutoCloseable {
}
}
String columnHeader(String id) {
return definitions.get(id).header();
}
private String headerText(String id) {
return definitions.get(id).header()
return columnHeader(id)
+ sortKeys.stream()
.filter(k -> k.columnId().equals(id))
.map(k -> k.direction() == SortKey.Direction.ASCENDING ? " ↑" : " ↓")
@@ -337,7 +377,8 @@ public final class TableResults<K, T> implements AutoCloseable {
Math.clamp(e.value(), c.minimumWidth(), c.maximumWidth()))
: width);
}
var nextHeader = headerNodes(nextOrder, preparedWidths);
var visibleOrder = visibleOrder(nextOrder);
var nextHeader = headerNodes(visibleOrder, preparedWidths);
result = List.copyOf(result);
Set<K> keys = new HashSet<>();
for (var row : result)
@@ -365,7 +406,7 @@ public final class TableResults<K, T> implements AutoCloseable {
next.add(new Entry<>(row, view, click, key));
validateRow(view);
view.root().getStyleClass().add("result-row");
layoutRow(view, nextOrder, preparedWidths);
layoutRow(view, visibleOrder, preparedWidths);
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
view.root().setFocusTraversable(true);
view.root().addEventHandler(KeyEvent.KEY_PRESSED, key);
@@ -379,7 +420,7 @@ public final class TableResults<K, T> implements AutoCloseable {
order = nextOrder;
widths.clear();
widths.putAll(preparedWidths);
header.getChildren().setAll(nextHeader);
replaceHeader(nextHeader);
captured = nextCaptured;
groupTree = nextTree;
grouping = nextGrouping.columns();
@@ -396,8 +437,7 @@ public final class TableResults<K, T> implements AutoCloseable {
validateOrder(ids);
order = ids;
drawHeader();
entries.forEach(e -> layoutRow(e.view()));
resizeGroupHeadings();
applyWidths(widths);
layoutCommitted.run();
}
@@ -455,7 +495,15 @@ public final class TableResults<K, T> implements AutoCloseable {
}
private void drawHeader() {
header.getChildren().setAll(headerNodes(order, widths));
replaceHeader(headerNodes(visibleOrder(order), widths));
}
private void replaceHeader(List<Node> cells) {
if (headerMenu != null) {
headerMenu.hide();
headerMenu = null;
}
header.getChildren().setAll(cells);
}
private List<Node> headerNodes(List<String> ordering, Map<String, ColumnWidth> sizes) {
@@ -501,6 +549,14 @@ public final class TableResults<K, T> implements AutoCloseable {
if (columnSeparators && !id.equals(ordering.getLast()))
cell.getChildren().add(ResultColumnSeparators.forHeader(cell));
gestures.header(cell, label, handle, id, () -> sortRequest.accept(id));
cell.setOnContextMenuRequested(event -> {
if (headerMenuFactory == null) return;
if (headerMenu != null) headerMenu.hide();
headerMenu = headerMenuFactory.apply(id, cell);
if (event.isKeyboardTrigger()) headerMenu.show(cell, Side.BOTTOM, 0, 0);
else headerMenu.show(cell, event.getScreenX(), event.getScreenY());
event.consume();
});
size(cell, width(id, sizes));
nodes.add(cell);
}
@@ -513,10 +569,6 @@ public final class TableResults<K, T> implements AutoCloseable {
region.setMaxWidth(width);
}
private void layoutRow(ResultRow view) {
layoutRow(view, order, widths);
}
private void layoutRow(ResultRow view, List<String> ordering, Map<String, ColumnWidth> sizes) {
Set<Region> fields = Collections.newSetFromMap(new IdentityHashMap<>());
fields.addAll(view.fields().values());
@@ -532,7 +584,7 @@ public final class TableResults<K, T> implements AutoCloseable {
else if (!fields.contains(child)) children.add(child);
}
if (columnSeparators) {
if (separators == null)
if (separators == null || !separators.matchesColumnCount(ordering.size()))
separators = new ResultColumnSeparators(view.root(), ordering.size());
separators.position(ordering.stream().mapToDouble(id -> width(id, sizes)).toArray());
children.add(separators);
@@ -543,7 +595,10 @@ public final class TableResults<K, T> implements AutoCloseable {
view.root().getScene() == null ? null : view.root().getScene().getFocusOwner();
boolean restore = focus != null && descendant(view.root(), focus);
view.root().getChildren().setAll(children);
if (restore) focus.requestFocus();
if (restore) {
if (descendant(view.root(), focus)) focus.requestFocus();
else view.root().requestFocus();
}
}
}
@@ -762,6 +817,7 @@ public final class TableResults<K, T> implements AutoCloseable {
.getChildren()
.getFirst()
.requestFocus();
else if (headerAccessory != null) headerAccessory.requestFocus();
}
}
resizeGroupHeadings();
@@ -862,8 +918,13 @@ public final class TableResults<K, T> implements AutoCloseable {
}
private void resizeGroupHeadings() {
double total = order.stream().mapToDouble(this::width).sum();
disclosure.values().forEach(button -> size(button, total));
resizeGroupHeadings(visibleOrder(order), widths);
}
private void resizeGroupHeadings(List<String> visible, Map<String, ColumnWidth> sizes) {
double total = visible.stream().mapToDouble(id -> width(id, sizes)).sum();
disclosure.values().forEach(
button -> size(button, visible.isEmpty() ? Region.USE_COMPUTED_SIZE : total));
}
void previewWidth(String id, ColumnWidth value) {
@@ -875,9 +936,9 @@ public final class TableResults<K, T> implements AutoCloseable {
private void applyWidths(Map<String, ColumnWidth> sizes) {
for (Node node : header.getChildren())
size((Region) node, width((String) node.getUserData(), sizes));
entries.forEach(e -> layoutRow(e.view(), order, sizes));
double total = order.stream().mapToDouble(id -> width(id, sizes)).sum();
disclosure.values().forEach(button -> size(button, total));
var visible = visibleOrder(order);
entries.forEach(e -> layoutRow(e.view(), visible, sizes));
resizeGroupHeadings(visible, sizes);
}
private void release(List<Entry<K, T>> retired) {
@@ -913,7 +974,7 @@ public final class TableResults<K, T> implements AutoCloseable {
var old = entries;
entries = List.of();
body.getChildren().clear();
header.getChildren().clear();
replaceHeader(List.of());
body.setOnMouseClicked(null);
selectedKey.set(null);
selectedElement.set(null);