*15.9 (使用箭头键画线)
- 请编写一个程序,使用箭头键绘制线段。所画的线从面板的中心开始,当敲 击向右、向上、向左或向下的箭头键时,相应地向东、向北、向西或向南方向画线,如图 15-26b所示
代码展示:编程练习题15_9DrawLinesUsingArrows.java
package chapter_15;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class 编程练习题15_9DrawLinesUsingArrows extends Application{
double x =150,y = 100;
@Override
public void start(Stage primaryStage) throws Exception {
Pane pane = new Pane();
pane.setOnKeyPressed(e ->{
switch (e.getCode()) {
case LEFT:{
Line line = new Line(x, y, x-5, y);
pane.getChildren().add(line);
x = line.getEndX();
y = line.getEndY();
break;
}
case RIGHT:{
Line line = new Line(x, y, x+5, y);
pane.getChildren().add(line);
x = line.getEndX();
y = line.getEndY();
break;
}
case UP:{
Line line = new Line(x, y, x, y-5);
x = line.getEndX();
y = line.getEndY();
pane.getChildren().add(line);
break;
}
case DOWN:{
Line line = new Line(x, y, x, y+5);
pane.getChildren().add(line);
x = line.getEndX();
y = line.getEndY();
break;
}
}
});
Scene scene = new Scene(pane, 300, 200);
primaryStage.setTitle("编程练习题15_9DrawLinesUsingArrows");
primaryStage.setScene(scene);
primaryStage.show();
pane.requestFocus();
}
public static void main(String[] args) {
Application.launch(args);
}
}
- 结果展示