Javafx 滑块:文本作为刻度标签 [英] Javafx slider: text as tick label
问题描述
我刚开始学习 Javafx,到目前为止我真的很喜欢它.但是,在我当前的项目中,我需要使用文本作为 javafx 滑块的刻度标签.我用谷歌搜索了很多,但找不到任何帮助.因此,例如,我想要一个有 4-5 个位置的滑块,它们是坏"、好"等,而不是 1、2、3、...
我知道我可以手动构建自定义 UI,并将标签放置在正确的位置,但我需要生成带有自定义文本的滑块,并且每次都具有不同的长度,所以它不起作用.例如,在 Swing 中可以使用哈希表更改标签,所以我的问题是,是否可以在 Javafx 中做到这一点?
这是一个使用 .
当您使滑块变小时,一些标签会消失,所以我在滑块上设置了一个最小宽度,以便标签保留(另一种解决方案,可能是设置一个新的标签格式化程序,如果滑块使用缩写标签尺寸小).
您可能也有兴趣投票或评论以下功能请求:RT-27863 LabelFormatter 不足以自定义 Slider 刻度.
I just started to learn Javafx, and I really like it so far. However in my current project I would need to use text as the tick labels for the javafx slider. I googled it a lot, but couldn't find any help. So for example I would like a slider with 4-5 positions, and them being "bad", "good", etc. instead of 1,2,3,...
I know I could build a custom UI manually with labels placed at the correct places, but I need to generate the sliders with custom text, and diofferent length every time, so it wouldn't work. In swing it is possible to change the labels with a hashtable for example, so my question is, is it possible to do it in Javafx?
Here is a sample using slider.setLabelFormatter.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class SlidingScale extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Slider slider = new Slider(0, 3, 0);
slider.setMin(0);
slider.setMax(3);
slider.setValue(1);
slider.setMinorTickCount(0);
slider.setMajorTickUnit(1);
slider.setSnapToTicks(true);
slider.setShowTickMarks(true);
slider.setShowTickLabels(true);
slider.setLabelFormatter(new StringConverter<Double>() {
@Override
public String toString(Double n) {
if (n < 0.5) return "Novice";
if (n < 1.5) return "Intermediate";
if (n < 2.5) return "Advanced";
return "Expert";
}
@Override
public Double fromString(String s) {
switch (s) {
case "Novice":
return 0d;
case "Intermediate":
return 1d;
case "Advanced":
return 2d;
case "Expert":
return 3d;
default:
return 3d;
}
}
});
slider.setMinWidth(380);
HBox layout = new HBox(slider);
layout.setPadding(new Insets(30));
primaryStage.setScene(new Scene(layout));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The sample above only works in Java 8 due to a bug in JavaFX 2.2.
Some of the labels disappear as you make the the slider smaller, so I set a min width on the slider so that the labels remain (an alternate solution, might be to set a new label formatter with abbreviated labels used if the slider is sized small).
You might also be interested in voting for or commenting on the following feature request: RT-27863 A LabelFormatter isn't enough to customize Slider ticks.
这篇关于Javafx 滑块:文本作为刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!