java - 在 JavaFX 中特定行数后截断文本
问题描述
是否可以在 JavaFX 中的固定行数之后截断标签或文本?对于 Web,有一个名为“line-clamp”的 CSS 属性。不幸的是,JavaFX 中似乎没有等价物。
使用标签,您可以选择换行或使用省略号截断文本。使用 Text 对象,至少可以指定换行。
未包装且未截断:
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eir mod tempor invidunt ut labore et dolore magna aliquyam
包装而不截断:
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore
magna aliquyam
未包装和截断:
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, ...
在 2 行后包装和截断(期望的行为):
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore ...
解决方案
我想出了相当基本的解决方案(可以进一步改进)。
public class MultiLineLabel extends VBox {
private final String text;
private final List<Label> lines = new ArrayList<>();
public MultiLineLabel(String text, int maxNumberOfLines) {
if (maxNumberOfLines < 1) {
throw new IllegalArgumentException();
}
this.text = text;
// Create num. of lines labels
for (int i=0; i<maxNumberOfLines; i++) {
final Label label = new Label();
lines.add(label);
label.setTextOverrun(OverrunStyle.CLIP);
}
getChildren().addAll(lines);
}
@Override
protected void layoutChildren() {
super.layoutChildren();
String remainingText = this.text;
for (Iterator<Label> iterator = lines.iterator(); iterator.hasNext(); ) {
final Label currentLine = iterator.next();
// If this is the last line, just set the text and finish
if (!iterator.hasNext()) {
currentLine.setText(remainingText);
currentLine.setTextOverrun(OverrunStyle.ELLIPSIS);
break;
} else {
final String textThatFitsInThisLine = Utils.computeClippedText(currentLine.getFont(), remainingText, this.getWidth(), OverrunStyle.CLIP, null);
currentLine.setText(textThatFitsInThisLine);
remainingText = remainingText.substring(textThatFitsInThisLine.length());
}
}
}
}
...然后可以像这样使用:
public class MultiLineLabelSSCCE extends Application {
@Override
public void start(Stage stage) {
final MultiLineLabel multiLineLabel =
new MultiLineLabel("This is some interesting text. The question is whether it's truncated properly. Let's see.", 3);
stage.setScene(new Scene(multiLineLabel));
stage.show();
}
}
演示(上述解决方案):
我希望这足以满足您的需要。
边注:
此解决方案基于com.sun.javafx.scene.control.skin.Utils
它被视为实现细节,而不是 JavaFx API 的一部分。要使用此解决方案运行代码,您可能需要添加:
--add-exports=javafx.controls/com.sun.javafx.scene.control.skin=org.example
到您的运行配置(VM 选项)
推荐阅读
- android - 有没有办法使用断言检查 jetpack compose 中嵌套组件的颜色?
- r - 从变量转移到数据框过滤
- gcloud - Google Cloud Composer 在欧洲西部的可用性4
- vaadin - Vaadin:为什么例如 HorizontalLayout 有一个 Shadow DOM
- latex - 在 PDF 的末尾放一个封底(latex,Rmarkdown)
- python - 在熊猫中迭代计算残差的移动平均值
- android - SignedCall Mockk 的匹配模拟签名失败
- java - 你如何在android上的代码中显示通知抽屉?
- c# - 将 C# 类强制转换为他的子类
- css - 在除一列之外的所有角度表中禁用自动缩放