Java实验(17) 赛车

绘制一辆赛车(颜色任选,款式如图),使用上下左右箭头控制赛车的移动。注意不能让赛车的任何部位超出界面的边界。


Java实验(17) 赛车_第1张图片


import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class TheMovingCar extends Application {
    @Override
    public void start(Stage primaryStage){
        BorderPane pane=new BorderPane();
        Group group=new Group();
        Rectangle r=new Rectangle(100,100,50,10);
        Circle c1=new Circle(115,113,5);
        Circle c2=new Circle(135,113,5);
        
        //画梯形
        Polygon p=new Polygon();
        ObservableList list=p.getPoints();
        list.addAll(120.0,90.0,110.0,100.0,140.0,100.0,130.0,90.0);
        
        r.setFill(Color.AQUAMARINE);
        c1.setFill(Color.BLUEVIOLET);
        c2.setFill(Color.GREENYELLOW);
        p.setFill(Color.DARKCYAN);    

        group.getChildren().addAll(p,r,c1,c2);
        
        group.setOnKeyPressed(e->{
            switch(e.getCode()){
                case DOWN:
                    if(group.getLayoutY()+10<=190)  
                        group.setLayoutY(group.getLayoutY()+10);
                    break;
                case UP:
                    if(group.getLayoutY()-10>=-90)  
                        group.setLayoutY(group.getLayoutY()-10);
                    break;
                case LEFT:
                    if(group.getLayoutX()-10>=-100)  
                        group.setLayoutX(group.getLayoutX()-10);
                    break;
                case RIGHT:
                    if(group.getLayoutX()+10<=160)  
                        group.setLayoutX(group.getLayoutX()+10);
                    break;
            }
        });
        
        pane.getChildren().add(group);
        Scene scene = new Scene(pane,300,300);
        primaryStage.setTitle("The Moving Car");
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setResizable(false);
        group.requestFocus();
    }
    public static void main(String[] args) {
        launch(args);
    }
} 


你可能感兴趣的:(Java实验)