Friday, June 17, 2016

39. ToggleButtton

A ToggleButton has two states: either selected or not selected (the selected button should appear a little darker).


Here the text of a label is bound to ToggleButton state. We could also use a listener, as in the commented code.


package ex39;
 
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class Ex39 extends Application {
 
    @Override
    public void start(Stage primaryStage) {
 
        ToggleButton toggleButton = new ToggleButton("toggleButton");
        Label label = new Label();
        label.setBackground(Background.EMPTY);
        toggleButton.setSelected(true);
        
        label.textProperty().bind(
                new SimpleStringProperty("state: ")
                        .concat(toggleButton.selectedProperty()
                                .asString()));
        
        /*toggleButton.setOnAction( e -> {
            label.setText("state: " + toggleButton.isSelected());
        });*/
                
        VBox root = new VBox(50, toggleButton, label);
        
        root.setAlignment(Pos.CENTER);
        root.setStyle("-fx-font-size: 16pt;"
                + "-fx-background-color: seashell;");
        
        Scene scene = new Scene(root, 400, 400);
        
        primaryStage.setTitle("Example 39. ToggleButtton");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

This is the output:


No comments:

Post a Comment