如何编辑JFXSpinner内部文本?能否修改其进度文本显示方式?
解决JFXSpinner的两个文本定制问题
一、编辑JFXSpinner的内部文本
JFXSpinner默认显示的是进度百分比,但如果想要自定义内部显示的文本内容(比如换成“加载中...”这类提示语),有两种可靠的实现方式:
方法1:利用progressFactory直接替换文本节点
JFXSpinner提供了progressFactory属性,允许你直接自定义显示进度的节点。这种方式简单直接,完全脱离默认的百分比逻辑:
JFXSpinner spinner = new JFXSpinner(); // 自定义内部文本和样式 spinner.setProgressFactory(progress -> { Label customLabel = new Label("正在加载,请稍候..."); customLabel.setStyle("-fx-text-fill: #2196F3; -fx-font-size: 14px;"); return customLabel; });
方法2:自定义Skin实现深度定制
如果需要同时调整动画和文本的底层逻辑,可以继承JFXSpinnerSkin并重写相关部分:
public class CustomSpinnerSkin extends JFXSpinnerSkin { private final Label customTextLabel; public CustomSpinnerSkin(JFXSpinner control) { super(control); // 创建自定义文本标签 customTextLabel = new Label("加载中..."); customTextLabel.setStyle("-fx-text-fill: #FF5722;"); // 替换默认的文本节点 getChildren().removeIf(node -> node instanceof Label); getChildren().add(customTextLabel); // 绑定位置,让文本居中显示 customTextLabel.layoutXProperty().bind(control.widthProperty().subtract(customTextLabel.widthProperty()).divide(2)); customTextLabel.layoutYProperty().bind(control.heightProperty().subtract(customTextLabel.heightProperty()).divide(2)); } } // 使用自定义Skin JFXSpinner spinner = new JFXSpinner(); spinner.setSkin(new CustomSpinnerSkin(spinner));
二、将进度文本从百分比改为0-1的数值索引格式
如果只是想修改进度的显示格式(比如把50%转换成0.5),只需要调整进度值的格式化逻辑即可,无需完全替换文本节点:
方式1:通过progressFactory格式化数值
JFXSpinner spinner = new JFXSpinner(); // 将0-1的进度值格式化为保留两位小数的数值 spinner.setProgressFactory(progress -> { String formattedValue = String.format("%.2f", progress); Label progressLabel = new Label(formattedValue); // 继承原Spinner的文本样式,保持视觉一致性 progressLabel.setStyle("-fx-text-fill: inherit; -fx-font-size: inherit;"); return progressLabel; }); // 测试:设置进度为75%,显示0.75 spinner.setProgress(0.75);
方式2:自定义Skin修改默认文本逻辑
如果你想保留原Spinner的所有默认样式,只改数值格式,可以直接修改默认Label的文本更新逻辑:
public class NumericProgressSpinnerSkin extends JFXSpinnerSkin { private final Label progressLabel; public NumericProgressSpinnerSkin(JFXSpinner control) { super(control); // 获取默认的进度标签 progressLabel = (Label) getChildren().stream() .filter(node -> node instanceof Label) .findFirst() .orElse(new Label()); // 监听进度变化,更新为0-1的数值格式 control.progressProperty().addListener((obs, oldVal, newVal) -> { double progress = newVal.doubleValue(); progressLabel.setText(String.format("%.2f", progress)); }); } } // 使用该Skin JFXSpinner spinner = new JFXSpinner(); spinner.setSkin(new NumericProgressSpinnerSkin(spinner)); spinner.setProgress(0.5); // 显示0.50
注意事项
- 尽量避免用
lookup()直接获取内部Label,JFoenix的内部组件结构可能随版本变化,导致代码失效。 - 如果需要更精确的数值显示,可以调整
String.format的格式参数(比如%.3f保留三位小数)。
内容的提问来源于stack exchange,提问作者TheZopo
相关产品推荐
相关产品推荐

