为什么 TextField 在运行时第一次更改其样式时会更改字体大小?

问题描述

检查句柄方法如下:

我打印出TextField的字体大小和样式,然后将其样式设置为新样式,将字体大小定义为其字体大小,然后再次打印出其字体大小和样式:

public class Control extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        VBox vBox = new VBox();
        final TextField textField = new TextField();
        Button button = new Button("set text and style");
        button.setonAction(new EventHandler<ActionEvent>()
        {
            public void handle(ActionEvent event)
            {
                System.out.println();
                System.out.println("Font size before: " +textField.getFont().getSize());
                System.out.println("Style before: " +textField.getStyle());
                textField.setText("button clicked");
                textField.setStyle("-fx-font-size: " + textField.getFont().getSize() + ";");
                System.out.println("Font size after: " + textField.getFont().getSize());
                System.out.println("Style after: " + textField.getStyle());
            }
        });
        textField.setStyle("-fx-font-size: 20;");
        vBox.getChildren().add(textField);
        vBox.getChildren().add(button);
        primaryStage.setScene(new Scene(vBox));
        primaryStage.show();
    }
    public static void startApp(String[] args)
    {
        launch(args);
    }
}

我创建了这个类作为最小的例子。

这是输出

Font size before: 20.0
Style before: -fx-font-size: 20;
Font size after: 11.686956405639648
Style after: -fx-font-size: 20.0;

Font size before: 20.0
Style before: -fx-font-size: 20.0;
Font size after: 20.0
Style after: -fx-font-size: 20.0;

Font size before: 20.0
Style before: -fx-font-size: 20.0;
Font size after: 20.0
Style after: -fx-font-size: 20.0;
...

如您所见,第一次更改样式后,字体大小为 11.68...,这对我来说很奇怪,为什么会发生这种情况?

使用 openjfx 15.0.1。

重现步骤:

  1. 复制上面的Control类并导入必要的东西
  2. 当然要包含 Javafx 依赖项
  3. 使用调用 Control.startApp(args) 的 main 方法创建另一个
  4. 运行并点击按钮几次

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)