Bind reusable commands to JavaFX action controls

This commit is contained in:
2026-11-23 18:24:22 +01:00
parent 981cd68f49
commit a3f7d2423f
10 changed files with 409 additions and 2 deletions
@@ -13,7 +13,7 @@ import java.util.Map;
* The list of binding elements declared inside {@code fx:define}.
* <p>
* The list is not a scene-graph child. FXML adds each {@link DirectBinding},
* {@link ComputedBinding}, or {@link Repeat} child to {@link #getElements()}.
* {@link ComputedBinding}, {@link CommandBinding}, or {@link Repeat} child to {@link #getElements()}.
*/
@DefaultProperty("elements")
public class BindingList {
@@ -48,6 +48,8 @@ public class BindingList {
DirectBindingApplier.apply(namespace, viewModel, directBinding, context, lifetime);
} else if (element instanceof ComputedBinding computedBinding) {
ComputedBindingApplier.apply(namespace, viewModel, controller, root, computedBinding, lifetime);
} else if (element instanceof CommandBinding commandBinding) {
CommandBindingApplier.apply(namespace, viewModel, commandBinding, lifetime);
} else if (element instanceof Repeat repeat) {
RepeatApplier.apply(namespace, viewModel, repeat, context, lifetime);
} else {
@@ -0,0 +1,39 @@
package de.neitzel.fx.view;
import java.util.Objects;
import javafx.beans.value.ObservableBooleanValue;
import lombok.Getter;
/**
* One action with a live availability rule. Use the command and its availability on the
* JavaFX application thread.
*/
public final class Command {
/** The availability observed by each control displaying this command. */
@Getter
private final ObservableBooleanValue canExecute;
private final Runnable action;
/**
* Creates a command for one action and execution context.
*
* @param canExecute live availability of the action
* @param action the work to start while the command is available
*/
public Command(ObservableBooleanValue canExecute, Runnable action) {
this.canExecute = Objects.requireNonNull(canExecute);
this.action = Objects.requireNonNull(action);
}
/**
* Executes the action after checking the current availability, including for keyboard
* shortcuts or callers without an attached control.
*/
public void execute() {
if (canExecute.get()) {
action.run();
}
}
}
@@ -0,0 +1,16 @@
package de.neitzel.fx.view;
import lombok.Getter;
import lombok.Setter;
/** Connects an FXML button or menu item to a command supplied by its ViewModel. */
@Getter
@Setter
public final class CommandBinding {
/** The target control's {@code fx:id}. */
private String control;
/** The simple bean property name of the command on the ViewModel. */
private String path;
}
@@ -0,0 +1,102 @@
package de.neitzel.fx.view;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.MenuItem;
final class CommandBindingApplier {
private CommandBindingApplier() {
}
static void validate(List<BindingList> lists, Map<String, Object> namespace) {
var commands = new IdentityHashMap<Object, CommandBinding>();
var propertyBindings = new ArrayList<Object>();
for (BindingList list : lists) {
for (Object element : list.getElements()) {
if (element instanceof CommandBinding binding) {
Object control = target(namespace, binding);
if (commands.put(control, binding) != null) {
throw invalid(namespace, binding, "duplicate owner for disable and onAction");
}
} else if (element instanceof DirectBinding binding) {
addConflict(propertyBindings, namespace, binding.getControl(), binding.getProperty());
} else if (element instanceof ComputedBinding binding) {
addConflict(propertyBindings, namespace, binding.getControl(), binding.getProperty());
}
}
}
for (Object control : propertyBindings) {
CommandBinding command = commands.get(control);
if (command != null) {
throw invalid(namespace, command, "another binding owns disable or onAction");
}
}
}
private static void addConflict(List<Object> targets, Map<String, Object> namespace,
String control, String property) {
if ("disable".equals(property) || "onAction".equals(property)) {
targets.add(namespace.get(control));
}
}
static void apply(Map<String, Object> namespace, Object viewModel, CommandBinding binding,
ViewLifetime lifetime) {
if (!lifetime.managed()) {
throw invalid(namespace, binding, "CommandBinding requires a ViewModelContext");
}
var target = target(namespace, binding);
var command = command(namespace, binding, viewModel);
try {
var registration = target instanceof ButtonBase button
? CommandBindings.bind(button, command) : CommandBindings.bind((MenuItem) target, command);
lifetime.own(registration::close);
} catch (IllegalArgumentException failure) {
throw invalid(namespace, binding, failure.getMessage());
}
}
private static Object target(Map<String, Object> namespace, CommandBinding binding) {
var target = namespace.get(binding.getControl());
if (target == null) {
throw invalid(namespace, binding, "unknown target fx:id");
}
if (!(target instanceof ButtonBase) && !(target instanceof MenuItem)) {
throw invalid(namespace, binding, "target must be a ButtonBase or MenuItem");
}
return target;
}
private static Command command(Map<String, Object> namespace, CommandBinding binding, Object viewModel) {
var path = binding.getPath();
if (path == null || path.isBlank() || path.contains(".")) {
throw invalid(namespace, binding, "expected a simple command path");
}
var getter = "get" + Character.toUpperCase(path.charAt(0)) + path.substring(1);
try {
var value = viewModel.getClass().getMethod(getter).invoke(viewModel);
if (value instanceof Command command) {
return command;
}
throw invalid(namespace, binding, getter + "() must return a Command instance");
} catch (NoSuchMethodException | IllegalAccessException failure) {
throw invalid(namespace, binding, "missing accessible command getter " + getter + "()");
} catch (InvocationTargetException failure) {
throw new IllegalArgumentException(
invalid(namespace, binding, "command getter " + getter + "() failed").getMessage(),
failure.getCause());
}
}
private static IllegalArgumentException invalid(Map<String, Object> namespace, CommandBinding binding,
String reason) {
return new IllegalArgumentException("Invalid CommandBinding in " + namespace.get(FXMLLoader.LOCATION_KEY)
+ " for " + binding.getControl() + " (disable/onAction), path " + binding.getPath() + ": " + reason);
}
}
@@ -0,0 +1,76 @@
package de.neitzel.fx.view;
import java.util.Map;
import java.util.Objects;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.MenuItem;
/** Attaches reusable commands to JavaFX action controls. */
public final class CommandBindings {
private static final Object REGISTRATION_KEY = new Object();
private CommandBindings() {
}
/** A single control's attachment to a command. Close on the JavaFX application thread. */
@FunctionalInterface
public interface Registration extends AutoCloseable {
/** Removes this attachment. Subsequent calls have no effect. */
@Override
void close();
}
/**
* Attaches the command to a button's action and disable properties.
*
* @param button the action control
* @param command the command to execute
* @return the attachment to close when the control is no longer in use
*/
public static Registration bind(ButtonBase button, Command command) {
return attach(button.getProperties(), button.disableProperty(), button.onActionProperty(), command);
}
/**
* Attaches the command to a menu item's action and disable properties.
*
* @param item the menu action
* @param command the command to execute
* @return the attachment to close when the menu item is no longer in use
*/
public static Registration bind(MenuItem item, Command command) {
return attach(item.getProperties(), item.disableProperty(), item.onActionProperty(), command);
}
private static Registration attach(Map<Object, Object> properties, BooleanProperty disable,
ObjectProperty<EventHandler<ActionEvent>> onAction, Command command) {
Objects.requireNonNull(command);
if (properties.containsKey(REGISTRATION_KEY) || disable.isBound()) {
throw new IllegalArgumentException("disable is already bound");
}
if (onAction.isBound() || onAction.get() != null) {
throw new IllegalArgumentException("onAction already has an owner");
}
var available = command.getCanExecute();
ChangeListener<Boolean> update = (observable, before, after) -> disable.set(!after);
EventHandler<ActionEvent> handler = event -> command.execute();
disable.set(!available.get());
onAction.set(handler);
available.addListener(update);
properties.put(REGISTRATION_KEY, handler);
return () -> {
if (properties.remove(REGISTRATION_KEY, handler)) {
available.removeListener(update);
if (onAction.get() == handler && !onAction.isBound()) {
onAction.set(null);
}
}
};
}
}
@@ -235,6 +235,7 @@ final class Components {
hasViewModel.setViewModel(bound);
}
Parent root = (Parent) component;
CommandBindingApplier.validate(lists, namespace);
for (BindingList list : lists) {
list.apply(namespace, viewModel, component, root, context, lifetime);
}
@@ -115,6 +115,7 @@ public final class ViewLoader {
if (controller instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
hasViewModel.setViewModel(bound);
}
CommandBindingApplier.validate(session.bindingLists(), loader.getNamespace());
for (BindingList bindingList : session.bindingLists()) {
bindingList.apply(loader.getNamespace(), viewModel, controller, root, context, lifetime);
}
@@ -0,0 +1,111 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.command.CommandController;
import de.neitzel.injection.ApplicationContext;
import java.nio.file.Files;
import java.nio.file.Path;
import javafx.scene.control.Button;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BindCommandTest {
@TempDir
Path directory;
@BeforeAll
static void start() throws InterruptedException {
FxThread.start();
}
@Test
void connectsOneCommandToButtonMenuAndKeyboardUntilClosed() throws Exception {
var url = view("commands.fxml", """
<CommandBinding control="button" path="clear"/>
<CommandBinding control="item" path="clear"/>
""");
FxThread.onFx(() -> {
try (var models = new ViewModelContext()) {
var view = ViewLoader.load(url, new CommandController.Subject(), services(), models);
var model = (CommandController.Model) view.getViewModel();
var button = (Button) view.getRoot().lookup("#button");
var menu = ((MenuBar) view.getRoot().lookup("#menu")).getMenus().getFirst();
var item = menu.getItems().getFirst();
var dynamic = new MenuItem();
try (var registration = CommandBindings.bind(dynamic, model.getClear())) {
assertTrue(button.isDisable());
assertTrue(item.isDisable());
item.fire();
model.getClear().execute();
assertEquals(0, model.getCalls());
model.getEnabled().set(true);
assertFalse(button.isDisable());
assertFalse(item.isDisable());
button.fire();
item.fire();
model.getClear().execute();
dynamic.fire();
assertEquals(4, model.getCalls());
}
dynamic.fire();
assertEquals(4, model.getCalls());
view.close();
assertNull(button.getOnAction());
assertNull(item.getOnAction());
model.getEnabled().set(false);
assertFalse(button.isDisable());
assertFalse(item.isDisable());
}
});
}
@Test
void rejectsUnknownTargetsAndConflictingOwners() throws Exception {
var scenarios = new String[][] {
{"<CommandBinding control='unknown' path='clear'/>", "unknown"},
{"<CommandBinding control='button' path='unknown'/>", "unknown"},
{"<CommandBinding control='menu' path='clear'/>", "ButtonBase or MenuItem"},
{"<CommandBinding control='button' path='clear'/><CommandBinding control='button' path='clear'/>", "duplicate"},
{"<CommandBinding control='button' path='clear'/><ComputedBinding control='button' property='disable' method='#unused'/>", "disable"}
};
for (var scenario : scenarios) {
var url = view("invalid-command.fxml", scenario[0]);
FxThread.onFx(() -> {
try (var models = new ViewModelContext()) {
var failure = assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(url, new CommandController.Subject(), services(), models));
assertTrue(failure.getMessage().contains("invalid-command.fxml"));
assertTrue(failure.getMessage().contains(scenario[1]));
}
});
}
}
private ApplicationContext services() {
return new ApplicationContext("de.neitzel.fx.view.command");
}
private java.net.URL view(String name, String bindings) throws Exception {
return Files.writeString(directory.resolve(name), """
<?import de.neitzel.fx.view.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.view.command.CommandController">
<fx:define><BindingList>%s</BindingList></fx:define>
<Button fx:id="button"/>
<MenuBar fx:id="menu"><menus><Menu><items><MenuItem fx:id="item"/></items></Menu></menus></MenuBar>
</VBox>
""".formatted(bindings)).toUri().toURL();
}
}
@@ -0,0 +1,27 @@
package de.neitzel.fx.view.command;
import de.neitzel.fx.view.Command;
import de.neitzel.fx.view.ViewModel;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Named;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import lombok.Getter;
@Named
@ViewModelClass(CommandController.Model.class)
public final class CommandController {
public static final class Subject { }
@Getter
public static final class Model extends ViewModel {
private final BooleanProperty enabled = new SimpleBooleanProperty();
private int calls;
private final Command clear = new Command(enabled, () -> calls++);
public Model(Subject bean) {
super(bean);
}
}
}