[英]JavaFX TextField resize with monospace font
我想创建一个自动调整大小到其内容大小的TextField。 如果我使用textField.prefColumnCountProperty().bind(textField.textProperty().length());
有用。 但是一旦我使用等宽字体,TextField会调整大小,但文本在我选择之前是不可见的。 如何使用等宽字体的resize属性?
在选择文本之前:
选择文字后:
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>
短:
仅当getAlignment()
设置为left( BASELINE_LEFT
, BOTTOM_LEFT
, CENTER_LEFT
或TOP_LEFT
)时才会出现此问题,因此只需使用textField.setAlignment(Pos.CENTER);
。
很长的答案,因为这仍然是一个奇怪的行为:
文本定位不正确,所有文本都移动到可见区域的左侧。 看起来这种行为的原因是文本字段的宽度很小。
这是一个小例子,其中键入文本“test”,然后将光标移动到左侧。
嗯,我想这是TextFieldSkin.computePrefWidth
如何工作的问题,因为它不计算光标的大小。
您可以创建自己的TextFieldSkin,computePrefWidth返回一个更大的值:(此代码示例使用com.sun.javafx.scene.control.skin.TextFieldSkin.TextFieldSkin
for 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.