首先,让我们按照您的建议创建一个滑块,其中包含三个主要刻度:
@Override
public void start(Stage primaryStage) {
Slider slider = new Slider(0, 10, 5);
slider.setMajorTickUnit(5);
slider.setMinorTickCount(0);
slider.setShowTickMarks(true);
slider.setSnapToTicks(true);
StackPane root = new StackPane(slider);
root.getStyleClass().add("pane");
Scene scene = new Scene(root, 300, 250);
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
style.css
文件中包含以下内容:
.pane {
-fx-background-color: #dcdcdc;
-fx-padding: 10;
}
.slider .axis .axis-tick-mark {
-fx-fill: null;
-fx-stroke: red;
}
现在让我们来检查坐标轴刻度线是如何创建的以及它们是什么类型的节点。为此,您可以选择以下任何一种选项:
现在使用lookup
更快。在舞台显示后添加调用:
primaryStage.show();
System.out.println("Axis-Tick-Mark: " + slider.lookup(".axis-tick-mark"));
然后它会打印出:
Axis-Tick-Mark: Path[elements=[MoveTo[x=0.0, y=0.0], LineTo[x=0.0, y=5.0], MoveTo[x=132.0, y=0.0], LineTo[x=132.0, y=5.0], MoveTo[x=264.0, y=0.0], LineTo[x=264.0, y=5.0]], fill=null, fillRule=NON_ZERO, stroke=0xff0000ff, strokeWidth=1.0]
这里有一个坐标轴刻度标记是一个Path
,它只是一个节点。这意味着您不能获得任何线条并以不同的方式对其进行样式化。
但是,如果您使用渐变修改`stroke`属性,则仍然可以将路径整体进行样式化。
因此,让我们添加一个根据您颜色的线性渐变:
.slider .axis .axis-tick-mark {
-fx-fill: null;
-fx-stroke-width: 2;
-fx-stroke: linear-gradient(to right, red, yellow, green);
}
这将按预期工作:
显然,您可以将其扩展到不同的设置(超过三个刻度),垂直方向,更多或不同的颜色...