JavaFX TextField使用等宽字体调整大小

时间:2018-05-15 07:31:54

标签: java javafx

我想创建一个自动调整大小到其内容大小的TextField。如果我使用textField.prefColumnCountProperty().bind(textField.textProperty().length());则可行。 但是一旦我使用等宽字体,TextField会调整大小,但文本在我选择之前是不可见的。如何使用等宽字体的resize属性?

在选择文字之前:

Before selecting the text

选择文字后

After selecting the text

Main.java

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java

package sample;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;


public class Controller {

    @FXML
    private TextField textField;

    @FXML
    public void initialize() {
        textField.setStyle("-fx-font-family: 'monospaced';");
        textField.prefColumnCountProperty().bind(textField.textProperty().length());
    }

}

sample.fxml

<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.TextField?>
<GridPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
        <TextField fx:id="textField"></TextField>
</GridPane>

1 个答案:

答案 0 :(得分:2)

<强>短

只有在getAlignment()设置为左BASELINE_LEFTBOTTOM_LEFTCENTER_LEFTTOP_LEFT时才会出现此问题,因此请使用textField.setAlignment(Pos.CENTER);

答案很长,因为这仍然是一种奇怪的行为:

文本位置不正确,所有文本都移到可见区域的左侧。看起来这种行为的原因是文本字段的宽度很小。

enter image description here

这是一个小例子,其中输入了文本“test”,然后将光标移动到左侧。

我想这是TextFieldSkin.computePrefWidth如何工作的问题,因为它不计算光标的大小。

您可以创建自己的TextFieldSkin,computePrefWidth返回一个更大的值:(此代码示例使用com.sun.javafx.scene.control.skin.TextFieldSkin.TextFieldSkin表示Java-8)

textField.setSkin(new TextFieldSkin(textField){
    @Override
    protected double computePrefWidth(double height, double topInset, double rightInset, double bottomInset, double leftInset) {
        return 1 + super.computePrefWidth(height, topInset, rightInset, bottomInset, leftInset);
    }
});

您还可以使用prefColumnCount

textField.prefColumnCountProperty().bind(textField.textProperty().length().add(1));

另见:What is the prefColumnCount property for a TextField?