Button newButton = new Button();
newButton.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("images/paper.png"))));
newButton.setId("newButton");
newButton.setTooltip(new Tooltip("New Document... Ctrl+N"));
newButton.setOnAction(e -> System.out.println("New toolbar button clicked"));
Defining Graphical Buttons
As shown in Figure 6-1, toolbar buttons often have a graphic rather than a title. They also often have a tooltip that pops up when the mouse cursor hovers over the button, as demonstrated in Step 4 of the exercise. In the following snippet from Listing 6-4, the toolbar button that causes a New Document to be created is defined with a graphic and tooltip, as well as an action to be performed when the toolbar button is selected:
Note that the setId() method of the Button is used in the preceding snippet. This causes the padding in the button to be set to four pixels on all four sides as a result of the following rule in the starterApp.css style sheet.
#newButton {
-fx-padding: 4 4 4 4;
}
The toolbar button defined in the previous code snippet is a JavaFX Button, but there are often use cases in which a JavaFX ToggleButton is a more appropriate choice. The following section discusses such cases, and how to implement toggle buttons in a toolbar.