Java Reference
In-Depth Information
We now give a program that adds three radio buttons named Red, Green, and Blue to the
preceding example to let the user choose the color of the message, as shown in FigureĀ 16.10.
VBox
containing
three radio
buttons
F IGURE 16.10
The program demonstrates using radio buttons.
Again there are at least two approaches to writing this program. The first is to revise the
preceding CheckBoxDemo class to insert the code for adding the radio buttons and process-
ing their events. The second is to define a subclass that extends CheckBoxDemo . Listing 16.4
gives the code to implement the second approach.
Application
L ISTING 16.4
RadioButtonDemo.java
1 import javafx.geometry.Insets;
2 import javafx.scene.control.RadioButton;
3 import javafx.scene.control.ToggleGroup;
4 import javafx.scene.layout.BorderPane;
5 import javafx.scene.layout.VBox;
6 import javafx.scene.paint.Color;
7
8 public class RadioButtonDemo extends CheckBoxDemo {
9 @Override // Override the getPane() method in the super class
10 protected BorderPane getPane() {
11 BorderPane pane = super .getPane();
12
13 VBox paneForRadioButtons = new VBox( 20 );
14 paneForRadioButtons.setPadding( new Insets( 5 , 5 , 5 , 5 ));
15 paneForRadioButtons.setStyle( "-fx-border-color: green" );
16 paneForRadioButtons.setStyle
17 ( "-fx-border-width: 2px; -fx-border-color: green" );
18 RadioButton rbRed = new RadioButton( "Red" );
19 RadioButton rbGreen = new RadioButton( "Green" );
20 RadioButton rbBlue = new RadioButton( "Blue" );
21 paneForRadioButtons.getChildren().addAll(rbRed, rbGreen, rbBlue);
22
ButtonDemo
CheckBoxDemo
RadioButtonDemo
override getPane()
invoke super.getPane()
pane for radio buttons
create radio buttons
pane.setLeft(paneForRadioButtons);
add to border pane
23
24
ToggleGroup group = new ToggleGroup();
group radio buttons
25
rbRed.setToggleGroup(group);
26
rbGreen.setToggleGroup(group);
27
rbBlue.setToggleGroup(group);
28
29 rbRed.setOnAction(e -> {
30 if (rbRed.isSelected()) {
31 text.setFill(Color.RED);
32 }
33 });
34
35 rbGreen.setOnAction(e -> {
36 if (rbGreen.isSelected()) {
37 text.setFill(Color.GREEN);
handle radio button
 
 
Search WWH ::




Custom Search