您的位置:首页 > 汽车 > 时评 > Java语言程序设计基础篇_编程练习题**15.19 (游戏:手眼协调)

Java语言程序设计基础篇_编程练习题**15.19 (游戏:手眼协调)

2024/10/18 13:10:49 来源:https://blog.csdn.net/2301_78998594/article/details/140625249  浏览:    关键词:Java语言程序设计基础篇_编程练习题**15.19 (游戏:手眼协调)

**15.19 (游戏:手眼协调)

  • 请编写一个程序,显示一个半径为10像素的实心圆,该圆放置在面板上的随机位置,并填充随机的顔色,如图15-29b所示。单击这个圆时,它会消失,然后在另一个随机的位置显示新的随机颜色的圆。在单击了20个圆之后,在面板上显示所用的时间,如图15-29c所示
  • 习题思路
  1.  新建一个面板Pane(),新建一个实心圆Circle,并将圆随机放置在面板上的一个位置,定义一个私有int类型count用于计数
  2. 获取当前的时间System.currentTimeMillis(),赋值给long类型startTime
  3. 为Circle注册一个事件(鼠标点击:SetOnMouseClick())
  4. 鼠标点击圆后将圆的位置再次随机设置
  5. 如果count等于20,获取当前时间,赋值给long endTimem,新建一个text表示时间,然后添加到pane中,同时从pane中移除Circle

代码示例:编程练习题15_19HandEyeCoordination.java 

package chapter_15;import javafx.application.Application;
import javafx.scene.Scene;
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_19HandEyeCoordination extends Application{private Pane pane = new Pane();private int count = 0;private Scene scene = new Scene(pane, 300, 300);@Overridepublic void start(Stage primaryStage) throws Exception {Circle circle = new Circle(10);circle.setFill(Color.RED); // 设置填充颜色circle.setStroke(Color.BLACK); // 设置边框颜色RandomLocation(circle);RandomColor(circle);pane.getChildren().add(circle);long startTime = System.currentTimeMillis();circle.setOnMouseClicked(e ->{RandomLocation(circle);RandomColor(circle);count++;if(count == 20) {long endTime = System.currentTimeMillis();long time = endTime - startTime ;Text text = new Text(pane.getWidth()/5, pane.getHeight()/2, "Time spent is "+time+" milliseconds");pane.getChildren().add(text);pane.getChildren().remove(circle);}});primaryStage.setTitle("编程练习题15_19HandEyeCoordination");primaryStage.setScene(scene);primaryStage.show();}public static void main(String[] args) {Application.launch(args);}public void RandomLocation(Circle circle) {double x = Math.random()*(pane.getWidth()-20)+10 ;double y = Math.random()*(pane.getHeight()-20)+10;circle.setCenterX(x);circle.setCenterY(y);}public void RandomColor(Circle circle) {circle.setFill(new Color(Math.random(), Math.random(), Math.random(), 1));}
}
  •  结果展示

 

版权声明:

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

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