We have a ComboBox with 3 options to select a different color.
Depending on the color, we paint the circle and set the label text. We also style the text to be 16 pt.
package ex26;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Ex26 extends Application {
// comboBox;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Example 26. ComboBox");
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll(
"Red",
"Green",
"Blue"
);
comboBox.setValue("Red");
Label label = new Label("Initial Color: Red");
Circle circle = new Circle(50, Color.RED);
comboBox.setPromptText("Color");
comboBox.setOnAction( e -> {
String col = comboBox.getValue();
label.setText("Selected Color: " + col);
switch(col) {
case "Red":
circle.setFill(Color.RED);
break;
case "Green":
circle.setFill(Color.GREEN);
break;
case "Blue":
circle.setFill(Color.BLUE);
break;
default:
break;
}
});
VBox layout = new VBox(50);
layout.setPadding(new Insets(50));
layout.getChildren().addAll(comboBox, label, circle);
layout.setStyle("-fx-font-size: 16pt;");
Scene scene = new Scene(layout, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
}
This is the output:
No comments:
Post a Comment