欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Java语言程序设计基础篇_编程练习题*15.3 (移动小球)

Java语言程序设计基础篇_编程练习题*15.3 (移动小球)

2024/11/30 9:40:44 来源:https://blog.csdn.net/2301_78998594/article/details/140540565  浏览:    关键词:Java语言程序设计基础篇_编程练习题*15.3 (移动小球)
*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{@Overridepublic 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 <0) {borderPane.setTop(text);return;}circle.setCenterX(circle.getCenterX()-circle.getRadius());});btRight.setOnMouseClicked(e->{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 < 0) {borderPane.setTop(text);return;}circle.setCenterY(circle.getCenterY()-circle.getRadius());});btDown.setOnMouseClicked(e->{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);}
}
  • 输出结果:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com