Action
class to centralize handling of properties and action handling. If two or
more controls that perform the same functionality the properties will be set to the action and the controls will be bound
to the action with related methods just like in the example below. In the example name, image, accelerator and action
handler are set for the action only. Predefined bind methods allow you to easily bind the related controls to the action.
Action newFileAction = new ActionBase("New File...");
newFileAction.setImage(new Image(getClass().getResource(iconLocation).toExternalForm()));
newFileAction.setAccelerator(KeyCombination.keyCombination("Shift+Ctrl+N"));
newFileAction.setHandler(e -> System.out.println(" -> Action: " + e));
...
MenuItem newFileMenuItem = new MenuItem();
newFileAction.bindMenuItem(newFileMenuItem, 16, 16);
...
Button newFileButton = new Button();
// -1 means use original icon size, last param is false to hide text
newFileAction.bindButton(newFileButton, -1, -1, false);
...
The screenshot below displays the result - the same icon is shown for the ToolBar
button and the related
MenuItem
. However, as usual in most business applications for the menuItem a different icon size is set
and text is hidden for the button only.
If you prefer to use vector over pixel based icons as i. e. provided by FontAwesomeFX
you can easily convert a node to an image by calling FXUtilitiess#asImage(Node)
.
Action newFileAction = new ActionBase("New File...");
newFileAction.setImage(createImage(FontAwesomeIcon.FILE_ALT));
newFileAction.setAccelerator(KeyCombination.keyCombination("Shift+Ctrl+N"));
newFileAction.setHandler(e -> System.out.println(" -> Action: " + e));
...
private Image createImage(FontAwesomeIcon icon){
FontAwesomeIconView node = new FontAwesomeIconView(icon);
node.setSize("2.8em");
node.setStyle("-fx-fill: #555");
// -1 means use original width/height
return FXUtilities.nodeAsImage(node, -1, -1);
}