我有一个 JavaFX 应用程序,我希望用户能够控制折线图中的符号、线条样式等。我不想创建多个样式表,而是想将此功能构建到 Java 代码中。感谢 Jewelsea 之前发布的优秀示例,我可以动态更改线条样式,这太棒了!但我无法更改默认符号样式。
我不清楚有多少 .css 语句可以在调用 node.setStyle 时逐字内联使用。即,我看到“-fx-*”命令可以在 Java 代码中运行。但是 .css 文件中的符号是用不同的语法定义的,仅仅将 css 行插入到我的 Java 代码中是行不通的。
这是我的代码中的一个示例:
StringBuilder styleString = new StringBuilder();
// do some stylin'
switch (getLineStyle.getValue().toString()) {
case "Line and points":
styleString.append("-fx-stroke: blue; -fx-stroke-width: 2; ");
styleString.append(
".chart-symbol {-fx-background-color: blue; -fx-background-radius: 3px;}");
engChart.setCreateSymbols(true);
break;
case "Line only":
styleString.append("-fx-stroke: blue; -fx-stroke-width: 2; ");
engChart.setCreateSymbols(false);
break;
Run Code Online (Sandbox Code Playgroud)
在“线和点”的情况下,我可以使用此代码控制颜色和宽度,但控制符号的尝试惨败。我从这里获取了语法:
http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#introscenegraph
如果有更好的参考用于执行此类内联控制,我很高兴知道它是什么。
谁能告诉我如何正确地内联操作这些符号?谢谢。
您不能在样式字符串中附加样式类定义。您只能在 css 文件中定义样式类。因此,创建并加载您自己的 css 文件,然后覆盖现有的符号样式或创建您自己的样式。
JavaFX 2.2 的默认样式表包含以下定义:
.chart-line-symbol {
-fx-background-color: #f9d900, white;
-fx-background-insets: 0, 2;
-fx-background-radius: 5px;
-fx-padding: 5px;
}
.default-color0.chart-line-symbol { -fx-background-color: #f9d900, white; }
.default-color1.chart-line-symbol { -fx-background-color: #a9e200, white; }
.default-color2.chart-line-symbol { -fx-background-color: #22bad9, white; }
.default-color3.chart-line-symbol { -fx-background-color: #0181e2, white; }
.default-color4.chart-line-symbol { -fx-background-color: #2f357f, white; }
.default-color5.chart-line-symbol { -fx-background-color: #860061, white; }
.default-color6.chart-line-symbol { -fx-background-color: #c62b00, white; }
.default-color7.chart-line-symbol { -fx-background-color: #ff5700, white; }
Run Code Online (Sandbox Code Playgroud)
因此,要么提供您自己的 .chart-line-symbol 定义,要么向图表添加新的样式类,例如chart.getStyleClass().add("custom-chart"),然后在 css 文件中定义自定义图表符号。
.custom-chart .chart-line-symbol {
-fx-background-color: #f9d900, firebrick;
-fx-background-radius: 0px;
}
Run Code Online (Sandbox Code Playgroud)
还有其他 方法可以实现图表符号的自定义样式,但最好仅使用 css,除非它确实不适用于您的用例。