Java语言程序设计基础篇

07-19 476阅读

*15.3 (移动小球)
  • 编写一个程序,在面板上移动小球。应该定义一个面板类来显示小球,并提供向左、 向右 、向上和向下移动小球的方法,如图15-24c所示。请进行边界检査以防止球完全移到视线之外

    代码展示:编程练习题15_3MoveBall.java

    package chapter_15;
    import javafx.application.Application;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    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.text.Text;
    import javafx.stage.Stage;
    public class 编程练习题15_3MoveBall extends Application{
    	@Override
    	public void start(Stage primaryStage) throws Exception {
    		BorderPane borderPane = new BorderPane();
    		Pane pane = new Pane();
    		HBox hBox = new HBox();
            pane.setPadding(new Insets(10, 10, 10, 10));
            hBox.setAlignment(Pos.CENTER);
            
            Circle circle = new Circle(150, 150, 20);
            circle.setFill(Color.WHITE);
            circle.setStroke(Color.BLACK);
            pane.getChildren().add(circle);
            
    		
    		Button btLeft = new Button("Left");
    		Button btRight = new Button("Right");
    		Button btUp = new Button("Up");
    		Button btDown = new Button("Down");
    		
    		Text text = new Text("下一个动作将越界!");
    		btLeft.setOnMouseClicked(e->{
    			borderPane.setTop(null);
    			if(circle.getCenterX()-circle.getRadius()*2 {
    			borderPane.setTop(null);
    			if(circle.getCenterX()+circle.getRadius()*2 > borderPane.getWidth()) {
    				borderPane.setTop(text);
    				return;
    			}
    			circle.setCenterX(circle.getCenterX()+circle.getRadius());
    		});
    		btUp.setOnMouseClicked(e->{
    			borderPane.setTop(null);
    			if(circle.getCenterY()-circle.getRadius()*2 {
    			borderPane.setTop(null);
    			if(circle.getCenterY()+circle.getRadius()*2 > borderPane.getHeight()) {
    				borderPane.setTop(text);
    				return;
    			}
    			circle.setCenterY(circle.getCenterY()+circle.getRadius());
    		});
    		
    		hBox.getChildren().addAll(btLeft, btRight, btUp, btDown);
    		
    		
    		borderPane.getChildren().add(pane);
    		borderPane.setBottom(hBox);
    		
    		Scene scene = new Scene(borderPane, 300, 300);
            primaryStage.setTitle("编程练习题14_3Poker");
            primaryStage.setScene(scene);
            primaryStage.show();
    	}
    	public static void main(String[] args) {
    		Application.launch(args);
    	}
    }
    
    • 输出结果:

      Java语言程序设计基础篇

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]