如何使JavaFX TextField的宽度动态增长?

huangapple go评论66阅读模式
英文:

How do I have a javafx TextField width grow dynamically?

问题

这似乎是一个简单的问题,但我似乎找不到任何在线答案。我有一个带有一些初始化文本的TextField,并且我想找到一种在用户在文本框中输入时增加TextField宽度的方法。例如,使用这段代码:

TextField iterations = new TextField("1000");
iterations.setPrefWidth(50);

宽度是50,但如果用户在框中输入了"1000000",我希望宽度能动态调整到足够宽。是否有简单的解决方案,还是我需要像添加事件处理程序一样不断调整宽度这样过度复杂的方法?

英文:

This seems like a simple question, but I can't seem to find any online answers. I have a TextField with some initialized text within it, and I want to find a way to grow the TextField width as the user types in the box. For example, with this code:

TextField iterations = new TextField("1000");
iterations.setPrefWidth(50);

The width is 50, but if the user typed "1000000" into the box I'd want the width to dynamically adjust to be just wide enough. Is there a simple solution for this, or would I need to do something overkill like adding EventHandlers to constantly adjust the width?

答案1

得分: 3

最简单的方法是将列数绑定到文本长度,但它看起来不太精确,因为TextField使用其列数来考虑字体中最宽字符:

iterations.prefColumnCountProperty().bind(
    Bindings.max(2, iterations.lengthProperty()));

(如果您只键入W字符,看起来还不错。)

一个更好看但更复杂的解决方案是使用TextField的皮肤来确定适当的大小:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.skin.TextFieldSkin;
import javafx.scene.layout.HBox;

public class GrowingTextField
extends Application {
    private double margin = -1;
    private double minWidth = -1;

    @Override
    public void start(Stage stage) {
        TextField iterations = new TextField(" ");
        iterations.setPrefColumnCount(2);
        iterations.skinProperty().addListener((o, old, skin) -> {
            if (skin != null && margin < 0) {
                TextFieldSkin textFieldSkin = (TextFieldSkin) skin;
                Platform.runLater(() -> {
                    margin = textFieldSkin.getCharacterBounds(0).getMinX();
                    minWidth = iterations.prefWidth(0);
                    Platform.runLater(() -> iterations.setText(""));
                });
            }
        });

        iterations.textProperty().addListener((o, oldText, text) -> {
            double width;
            if (text.length() <= iterations.getPrefColumnCount()) {
                width = minWidth;
            } else {
                TextFieldSkin skin = (TextFieldSkin) iterations.getSkin();
                double left = skin.getCharacterBounds(0).getMinX();
                double right = skin.getCharacterBounds(
                    text.offsetByCodePoints(text.length(), -1)).getMaxX();
                width = right - left + margin * 2;
            }
            Platform.runLater(() -> iterations.setPrefWidth(width));
        });

        HBox pane = new HBox(iterations);
        pane.setPadding(new Insets(12));

        stage.setScene(new Scene(pane, 800, 150));
        stage.setTitle("Growing TextField");
        stage.show();
    }

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

我不明白为什么需要这样做。为什么不一开始就给TextField一个较大的列数,就像网页浏览器的URL字段一样?

英文:

The easiest approach is to bind the column count to the text length, but it won’t look very accurate, since a TextField uses its column count to account for the widest characters of the font:

iterations.prefColumnCountProperty().bind(
Bindings.max(2, iterations.lengthProperty()));

(Looks pretty good if you only type W characters.)

A better-looking, but more complicated, solution is to use the TextField’s skin to figure out the proper size:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.skin.TextFieldSkin;
import javafx.scene.layout.HBox;
public class GrowingTextField
extends Application {
private double margin = -1;
private double minWidth = -1;
@Override
public void start(Stage stage) {
TextField iterations = new TextField(&quot; &quot;);
iterations.setPrefColumnCount(2);
iterations.skinProperty().addListener((o, old, skin) -&gt; {
if (skin != null &amp;&amp; margin &lt; 0) {
TextFieldSkin textFieldSkin = (TextFieldSkin) skin;
Platform.runLater(() -&gt; {
margin = textFieldSkin.getCharacterBounds(0).getMinX();
minWidth = iterations.prefWidth(0);
Platform.runLater(() -&gt; iterations.setText(&quot;&quot;));
});
}
});
iterations.textProperty().addListener((o, oldText, text) -&gt; {
double width;
if (text.length() &lt;= iterations.getPrefColumnCount()) {
width = minWidth;
} else {
TextFieldSkin skin = (TextFieldSkin) iterations.getSkin();
double left = skin.getCharacterBounds(0).getMinX();
double right = skin.getCharacterBounds(
text.offsetByCodePoints(text.length(), -1)).getMaxX();
width = right - left + margin * 2;
}
Platform.runLater(() -&gt; iterations.setPrefWidth(width));
});
HBox pane = new HBox(iterations);
pane.setPadding(new Insets(12));
stage.setScene(new Scene(pane, 800, 150));
stage.setTitle(&quot;Growing TextField&quot;);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Output

如何使JavaFX TextField的宽度动态增长?


I do question why one would need this. Why not just give the TextField a large column count to start with, like a web browser’s URL field?

huangapple
  • 本文由 发表于 2023年5月24日 18:05:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定