gpt4 book ai didi

java - 在 JavaFX 中切换组件的颜色

转载 作者:行者123 更新时间:2023-11-30 07:12:32 25 4
gpt4 key购买 nike

如果我有一个 JavaFX 对象的实例,比如一个 AnchorPane,我该如何切换它的背景/前景颜色?我进行了快速的 Google 搜索,结果一无所获,而且通过探索它的方法,也没有像 setColor() 这样明显的东西。

最佳答案

一般建议

任何需要 Paint 的东西作为参数将允许您设置颜色,如 Color源自 Paint。

组件样式有多种方式,一般来说,使用css通常是首选,因为它允许您以声明方式设置场景图的样式,与程序逻辑分开。当您的应用程序切换到维护模式时,这使得修改和更新样式变得更加容易。

使用 CSS

简单的CSS样式应用:

anchorPane.setStyle("-fx-background-color: cornsilk;");

就 css 应用而言,建议使用样式表而不是上面的 setStyle 调用。您可以在以下答案中查看 JavaFX 中不同样式应用程序的解释:In JavaFX, should I use CSS or setter methods to change properties on my UI Nodes? .

应用样式表的示例:

scene.getStylesheets().add(getClass().getResource("pane.css").toExternalForm());
myAnchorPane.getStyleClass().add("colored-pane");

还有一个设置所有 AnchorPanes 背景颜色的样式表:

/** `pane.css` in the same directory as your application class **/
.colored-pane { -fx-background-color: cornsilk; }

使用 Java 8 后台 API

Java 8 引入了一个新的 API,通过 Background 以编程方式控制背景。类(class)。

pane.setBackground(
new BackgroundFill(
Color.CRIMSON, CornerRadii.EMPTY, Insets.EMPTY
)
);

请注意,背景(无论是在 css 中定义还是通过背景 API 定义)仅适用于某些类型的节点(例如区域、布局和控件)。

设置形状属性

A Shape定义了一些您可以设置以更改形状颜色的属性。常见的形状有圆形、矩形、路径和文本。

stroke :

a stroke that is drawn around the outline of a Shape 
using the settings of the specified Paint.

fill :

fill the interior of an Shape using the settings of the Paint context.

填充和描边示例:

// draws a green square with a thick blue border.
Rectangle square = new Rectangle(30, 30, 50, 50);
square.setFill(Color.GREEN);
square.setStroke(Color.BLUE);
square.setStrokeWidth(6);

Canvas GraphicsContext

许多 JavaFX 基于场景图中的声明性定义、fxml 和 css,而不是像 setColor() 这样的显式命令式命令。我的意思是你发出命令的顺序并没有太大的不同。如果您想使用更传统的绘图方法,通过将系统置于一种模式,其中所有后续命令都作用于定义当前绘图属性(例如填充和描边样式)的上下文,请使用 Canvas .

// paint two blue rectangles on a canvas.
final Canvas canvas = new Canvas(250,250);
GraphicsContext gc = canvas.getGraphicsContext2D();

gc.setFill(Color.BLUE);
gc.fillRect(75,75,100,100);
gc.fillRect(25,25,30,30);

但一般来说,对于很多事情,SceneGraph 比 Canvas 更适合使用,因为您在更高的抽象级别上工作。 Canvas GraphicsContext确实有一个简单、直接的 API 的优势,尽管它都是在一个类中定义的。它还可用于将代码从其他系统(例如 HTML5 canvas)移植到 JavaFX。

关于java - 在 JavaFX 中切换组件的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com