下面的实例用不同的颜色、方向重复显示一行文字。
本实例代码如下:
import java.util.Random;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ColorText extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 250, Color.WHITE);
Random rand = new Random(System.currentTimeMillis());
for (int i=0; i<100; i++) {
int x = rand.nextInt((int)scene.getWidth());
int y = rand.nextInt((int)scene.getHeight());
int red = rand.nextInt(255);
int green = rand.nextInt(255);
int blue = rand.nextInt(255);
Text text = new Text(x,y, "JavaFx Programing 冯斌");
int rot = rand.nextInt(360);
text.setFill(Color.rgb(red,green, blue, .99));
text.setRotate(rot);
root.getChildren().add(text);
}
primaryStage.setTitle("ColorText");
primaryStage.setScene(scene);
primaryStage.show();
}
}
运行结果如下:
说明:
1、自从JDK最初版本发布起,我们就可以使用java.util.Random类产生随机数了。在JDK1.2中,Random类有了一个名为nextInt()的方法:
public int nextInt(int n)
给定一个参数n,nextInt(n)将返回一个大于等于0小于n的随机数,即: 0<= nextInt(n) < n。
2、System.currentTimeMillis()它返回从 UTC 1970 年 1 月 1 日午夜开始经过的毫秒数。
3、new Random()构造方法使用的种子是当前System.currentTimeMillis(),所以上面代码:Random rand = new Random(System.currentTimeMillis());可以简写为Random rand = new Random();
4、Group root = new Group();可以改成Pane pane = new Pane();
转载于:https://blog.51cto.com/fengbin8606/1575124