Friday, June 24, 2016

73. ColorPicker and DatePicker

The ColorPicker can select a color. We bind it to a label as well as the scene fill color.


The DatePicker can select a date. We bind it to a label.


package ex73;

import java.time.LocalDate;
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Ex73 extends Application {

    @Override
    public void start(Stage stage) {
        
        String date = "2016-06-23";
        
        ObjectProperty str1 =
                new SimpleObjectProperty<>(this,"str1",Color.WHITE);
        StringProperty str2 = 
                new SimpleStringProperty(this,"str2",date);
        
        Font font = Font.font("Georgia", 20);
        
        Label label1 = new Label();
        label1.setFont(font);
        label1.setLayoutX(100); label1.setLayoutY(100);
        Label label2 = new Label();
        label2.setFont(font);
        label2.setLayoutX(100); label2.setLayoutY(200);
        Label label3 = new Label("Color: ");
        label3.setFont(font);
        label3.setLayoutX(50); label3.setLayoutY(350);
        Label label4 = new Label("Date: ");
        label4.setFont(font);
        label4.setLayoutX(50); label4.setLayoutY(450);
        
        ColorPicker colorPicker = new ColorPicker();
        colorPicker.setOnAction(event -> 
                str1.set(colorPicker.getValue()));
        colorPicker.setLayoutX(150); colorPicker.setLayoutY(350);
        
        LocalDate dateLD = LocalDate.parse(date);
        DatePicker datePicker = new DatePicker(dateLD);
        datePicker.setOnAction(event -> {
            LocalDate localDate = datePicker.getValue();
            str2.set(localDate.toString());
        });
        datePicker.setLayoutX(150); datePicker.setLayoutY(450);
        
        Group root = new Group(label1, label2,
                label3, label4, 
                colorPicker, datePicker);
        
        Scene scene = new Scene(root, 400, 550);
        stage.setTitle("Example 73. ColorPicker and DatePicker"); 
        
        label1.textProperty().bind(new SimpleStringProperty("Color: ")
                .concat((str1.asString())));
        label2.textProperty().bind(new SimpleStringProperty("Date: ")
                .concat(str2));
        scene.fillProperty().bind(str1);
        
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

This is the output after selecting a date and color:


No comments:

Post a Comment