JavaFX - 颜色( Colors)
要将颜色应用于应用程序,JavaFX在包javafx.scene.paint包中提供了各种类。 这个包包含一个名为Paint的抽象类,它是用于应用颜色的所有类的基类。
使用这些类,您可以使用以下模式应用颜色 -Uniform - 在此模式中,颜色在整个节点中均匀应用。
Image Pattern - 这使您可以使用图像模式填充节点的区域。
Gradient - 在此模式中,应用于节点的颜色从一个点到另一个点不同。 它有两种梯度,即Linear Gradient和Radial Gradient 。
您可以应用颜色的所有节点类(如Shape, Text (包括Scene))都具有名为setFill()和setStroke() 。 这些将有助于分别设置节点的颜色值及其笔划。
这些方法接受Paint类型的对象。 因此,要创建这些类型的图像中的任何一种,您需要实例化这些类并将对象作为参数传递给这些方法。
将颜色应用于节点
要为节点设置统一的颜色模式,需要将类颜色的对象传递给setFill() , setStroke()方法,如下所示 -//Setting color to the text
Color color = new Color.BEIGE
text.setFill(color);
//Setting color to the stroke
Color color = new Color.DARKSLATEBLUE
circle.setStroke(color);
在上面的代码块中,我们使用颜色类的静态变量来创建颜色对象。
同样,您也可以使用RGB值或HSB标准的着色或Web哈希码的颜色,如下所示 -//creating color object by passing RGB values
Color c = Color.rgb(0,0,255);
//creating color object by passing HSB values
Color c = Color.hsb(270,1.0,1.0);
//creating color object by passing the hash code for web
Color c = Color.web("0x0000FF",1.0);
例子 (Example)
下面是一个演示如何将颜色应用于JavaFX中的节点的示例。 在这里,我们创建一个圆形和文本节点并为它们应用颜色。
将此代码保存在名为ColorExample.java的文件中。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.text.Font;
import javafx.scene.text.Text;
public class ColorExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(180.0f);
circle.setRadius(90.0f);
//Setting color to the circle
circle.setFill(Color.DARKRED);
//Setting the stroke width
circle.setStrokeWidth(3);
//Setting color to the stroke
circle.setStroke(Color.DARKSLATEBLUE);
//Drawing a text
Text text = new Text("This is a colored circle");
//Setting the font of the text
text.setFont(Font.font("Edwardian Script ITC", 50));
//Setting the position of the text
text.setX(155);
text.s