如何在 JavaFX 中为节点添加颜色?
使用 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) {
//Drawing a circle
Circle circle = new Circle(75.0f, 65.0f, 40.0f );
//Drawing a Rectangle
Rectangle rect = new Rectangle(150, 30, 100, 65);
//Drawing an ellipse
Ellipse ellipse = new Ellipse(330, 60, 60, 35);
//Drawing Polygon
Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
//Color by name
circle.setFill(Color.CHOCOLATE);
circle.setStrokeWidth(5);
circle.setStroke(Color.DARKRED);
//Using RGB
rect.setFill(Color.rgb(150, 0, 255));
rect.setStrokeWidth(5);
rect.setStroke(Color.DARKRED);
//Using HSB
ellipse.setFill(Color.hsb(50, 1, 1));
ellipse.setStrokeWidth(5);
ellipse.setStroke(Color.DARKRED);
//Using web
poly.setFill(Color.web("#E9967A"));
poly.setStrokeWidth(5);
poly.setStroke(Color.DARKRED);
//Setting the stage
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);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP