Java實驗(17) 賽車

繪製一輛賽車(顏色任選,款式如圖),使用上下左右箭頭控制賽車的移動。注意不能讓賽車的任何部位超出界面的邊界。



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<Double> 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);
    }
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章