使用JavaFX CSS将文本大小写转换为大写

4

有人能帮我在JavaFX项目中更改大小写吗?我试着浏览找到解决方案,但是我找不到。请看下面的代码,我正在尝试但是无法得到结果。

.text {
    -fx-font-family: "Arial";
    -fx-font-size: 24;
    -fx-text-fill: #263248;
    -fx-padding: 10 20 10 20;
    -fx-cursor: hand;
    -fx-text-transform: uppercase; /* this property is not working */ 
}

任何帮助都将不胜感激!谢谢!

-fx-text-transform 是 JavaFX 的 CSS 属性吗?我不这么认为。 - ItachiUchiha
我已经进行了注释,我只需要那一行的解决方案... 那一行的确切代码是什么? - Karthi Keyan
你无法使用CSS实现你想要的效果,你需要在Java代码中实现它。 - ItachiUchiha
2
你可以随时将控制器分配给FXML,并在initialize(..)内进行必要的代码安排。有关更多信息,请查看精通FXML - ItachiUchiha
1
然后向您的控件添加一个监听器,并使用方法 toUpperCase()。一个简单的示例在这个答案中。 - ItachiUchiha
显示剩余2条评论
3个回答

1
很遗憾,在JavaFX中没有处理文本转换的CSS属性(目前没有,参见JavaFX CSS参考)。但是,实际上您可以在Java中仅使用一行代码来完成此操作!
例如,您有一个名为label的ID的Label节点。
<Label fx:id="label" text="Hello!" />

在这种情况下,您可以通过其ID引用node并使用控制器类将其文本toUpperCase()
// Reference to the node you wish
// to transform texts to uppercase.
@FXML private Label label;

@Override
// Assuming you have Initializable class implemented.
public void initialize(URL arg0, ResourceBundle arg1) {

  // Get the current text value of the node.
  String text = label.getText();

  // Then update the text into whatever case you like.
  label.setText(text.toUpperCase());

}

或者

只需一行Java代码即可实现(直接从Java代码中复制)。

Label label = new Label("Hello!".toUpperCase());

感谢您的时间,我会检查! - Karthi Keyan

1
这是一种通用的方法。 您可以在styleClass中标记所需的内容为upper和lower,然后调用此方法:
public static void textTransform(@NotNull Node root) {
    _textTransform(root, ".upper");
    _textTransform(root, ".lower");
}
private static void _textTransform(@NotNull Node root, @NotNull String selector) {
    boolean upper = selector.equalsIgnoreCase(".upper");
    for (Node node : root.lookupAll(selector)) {
        if (node instanceof Text) {
            Text text = (Text) node;
            text.setText(upper ? text.getText().toUpperCase() : text.getText().toLowerCase());
        } else
        if (node instanceof Label) {
            Label label = (Label) node;
            label.setText(upper ? label.getText().toUpperCase() : label.getText().toLowerCase());
        } else
        if (node instanceof Button) {
            Button button = (Button) node;
            button.setText(upper ? button.getText().toUpperCase() : button.getText().toLowerCase());
        }
    }
}

0

您可以向文本添加ChangeListener:

Text text;
//...
text.textProperty().add(
    (observer, oldValue, newValue) -> text.setText(newValue.toUpperCase())
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接