您可以使用setFill()和setStroke()方法将颜色应用于JavaFX中的节点。 setFill()方法增加了颜色的节点,而表面积setStroke()方法应用于彩色到节点的边界。
这两种方法都接受javafx.scene.paint.Paint类的对象作为参数。它是颜色和渐变的基类,用于用颜色填充形状和背景。
JavaFX中的javafx.scene.paint.Color类是Paint的子类,它将所有颜色封装在RGB颜色空间中(作为其属性)。
要将颜色应用于几何形状或背景或形状的笔触,需要通过传递表示所需颜色的Color对象来调用相应的方法。
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class ColorExample extends Application {
public void start(Stage stage) {
//画一个圆
Circle circle = new Circle(75.0f, 65.0f, 40.0f );
//画一个矩形
Rectangle rect = new Rectangle(150, 30, 100, 65);
//画一个椭圆
Ellipse ellipse = new Ellipse(330, 60, 60, 35);
//绘制多边形
Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
//颜色按名称
circle.setFill(Color.CHOCOLATE);
circle.setStrokeWidth(5);
circle.setStroke(Color.DARKRED);
//使用RGB-
rect.setFill(Color.rgb(150, 0, 255));
rect.setStrokeWidth(5);
rect.setStroke(Color.DARKRED);
//使用HSB-
ellipse.setFill(Color.hsb(50, 1, 1));
ellipse.setStrokeWidth(5);
ellipse.setStroke(Color.DARKRED);
//使用网页
poly.setFill(Color.web("#E9967A"));
poly.setStrokeWidth(5);
poly.setStroke(Color.DARKRED);
//设置舞台
Group root = new Group(circle, ellipse, rect, poly);
Scene scene = new Scene(root, 600, 150);
stage.setTitle("Setting Colors");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出结果