Java Reference
In-Depth Information
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.
Defining Toggle Buttons
In Steps 5 and 6 of the preceding exercise, you interacted with buttons that have two states: selected and not selected.
The buttons in Step 5 are toggle buttons, as are the buttons in Step 6. The buttons in Step 5 operate independently
of each other, but only one of the buttons in Step 6 can be in the selected (depressed) state at any given time. The
following snippet from Listing 6-4 contains the code behind one of the buttons in Step 5.
ToggleButton boldButton = new ToggleButton();
boldButton.setGraphic(new Circle(8, Color.MAROON));
boldButton.setId("boldButton");
boldButton.setOnAction(e -> {
ToggleButton tb = ((ToggleButton) e.getTarget());
System.out.print(e.getEventType() + " occurred on ToggleButton "
+ tb.getId());
System.out.print(", and selectedProperty is: ");
System.out.println(tb.selectedProperty().getValue());
});
This use case is the classic Bold button in many document editing applications, where the Bold button is either
selected or not selected. The
ToggleButton
shown in the preceding snippet contains this dual-state functionality, so it
is a natural fit for this use case.
The
onAction()
event handler in this snippet demonstrates how you can ascertain the state of the
ToggleButton
as a result of being clicked. As shown in the snippet, use the
getTarget()
method of the
ActionEvent
to obtain a
reference to the
ToggleButton
; then use its
selectedProperty()
method to get a reference to its
selected
property.
Finally, use the
getValue()
method to get the value (either true or false) of the selected property.
Using Toggle Groups
As pointed out in the previous section, only one of the buttons in Step 6 of the preceding exercise can be in the
selected (depressed) state at any given time. The following snippet from Listing 6-4 contains the code behind one of
the buttons in Step 6.
final ToggleGroup alignToggleGroup = new ToggleGroup();
ToggleButton leftAlignButton = new ToggleButton();
leftAlignButton.setGraphic(new Circle(8, Color.PURPLE));
leftAlignButton.setId("leftAlignButton");
leftAlignButton.setToggleGroup(alignToggleGroup);
...
Search WWH ::
Custom Search