目录
题目:**16.3 (交通信号灯)
编写一个程序来模拟交通信号灯。程序可以让用户从红、黄、绿三种顔色灯中选择一种。当选择一个单选按钮后,相应的灯被打开,并且一次只能亮一种灯(如图16-37a所示)。程序开始时所有的灯都是不亮的
-
习题思路
- 新建一个Pane,绘制一个Rectangle和三个Circle,并添加到Pane中
- 新建一个HBox, 创建三个单选按钮(RadioButton),按钮加入组中(ToggleGroup),按钮被选择时把对应的Circle的设置为对应的颜色,同时把其他灯设置为透明
- 新建一个BorderPane,把Pane放置在中心,把HBox放置在底部
代码示例
编程练习题16_3TrafficLight.java
package chapter_16;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class 编程练习题16_3TrafficLight extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
Pane pane = new Pane();
double x = 200;
double y = 100;
Rectangle rectangle = new Rectangle(x-20, y-55, 40, 110);
rectangle.setFill(Color.TRANSPARENT);
rectangle.setStroke(Color.BLACK);
Circle red = new Circle(x, y-35, 15);
red.setFill(Color.TRANSPARENT);
red.setStroke(Color.BLACK);
Circle yellow = new Circle(x, y, 15);
yellow.setFill(Color.TRANSPARENT);
yellow.setStroke(Color.BLACK);
Circle green = new Circle(x, y+35, 15);
green.setFill(Color.TRANSPARENT);
green.setStroke(Color.BLACK);
pane.getChildren().addAll(red, yellow, green,rectangle);
HBox hBox = new HBox(20);
hBox.setPadding(new Insets(5, 5, 5, 5));
hBox.setAlignment(Pos.CENTER);
RadioButton rbRed = new RadioButton("Red");
RadioButton rbYellow = new RadioButton("Yellow");
RadioButton rbGreen = new RadioButton("Green");
ToggleGroup group = new ToggleGroup();
rbRed.setToggleGroup(group);
rbYellow.setToggleGroup(group);
rbGreen.setToggleGroup(group);
hBox.getChildren().addAll(rbRed, rbYellow, rbGreen);
rbRed.setOnAction(e ->{
if(rbRed.isSelected()) {
yellow.setStyle("-fx-fill:TRANSPARENT");
green.setStyle("-fx-fill:TRANSPARENT");
red.setStyle("-fx-fill:red");
}
});
rbYellow.setOnAction(e ->{
if(rbYellow.isSelected()) {
yellow.setStyle("-fx-fill:yellow");
green.setStyle("-fx-fill:TRANSPARENT");
red.setStyle("-fx-fill:TRANSPARENT");
}
});
rbGreen.setOnAction(e ->{
if(rbGreen.isSelected()) {
yellow.setStyle("-fx-fill:TRANSPARENT");
green.setStyle("-fx-fill:green");
red.setStyle("-fx-fill:TRANSPARENT");
}
});
BorderPane borderPane = new BorderPane();
borderPane.setCenter(pane);
borderPane.setBottom(hBox);
Scene scene = new Scene(borderPane, 400, 220);
primaryStage.setTitle("编程练习题16_3TrafficLight");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
-
结果展示