java - 自动扩展 TextField 以适合文本

标签 java javafx

我想创建一个随着输入更多文本而水平扩展的文本字段。

prefColumnCount 属性绑定(bind)到 TextField 中文本的长度后,其大小会随着文本变长而增加。但是,插入符号的位置不会更新,并且无论文本长度如何,它都会卡在同一位置。用户必须手动将插入符号移到前面才能正确显示。

图片:

输入一些文本后的样子,文本没有占据整个文本字段:

将插入符号移动到文本开头后:

这是我当前的代码:

TextField textField = new TextField();
textField.prefColumnCountProperty().bind(textField.textProperty().length());
setHgrow(textField, Priority.ALWAYS);

如何解决这个问题?如有任何帮助,我们将不胜感激!

最佳答案

此示例在其自己的 css 样式场景中使用单独的测量文本变量来计算对 TextField 的首选大小的更新,以便其首选大小根据需要扩展和缩小。

short text

long text

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class MagicExpander extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        TextField textField = new ExpandingTextField();

        Pane layout = new VBox(textField);
        layout.setPadding(new Insets(10));

        stage.setScene(new Scene(layout, 600, 40));
        stage.show();
    }

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

    static class ExpandingTextField extends TextField {
        private static int MAGIC_PADDING = 20;

        private Text measuringText = new Text();
        // To allow potential css formatting to work for the text,
        // it is required that text be placed in a Scene,
        // even though we never explicitly use the scene.
        private Scene measuringScene = new Scene(new Group(measuringText));

        ExpandingTextField() {
            super();
            setPrefWidth(MAGIC_PADDING);
            setMinWidth(MAGIC_PADDING);
            setMaxWidth(USE_PREF_SIZE);

            // note if the text in your text field is styled, then you should also apply the
            // a similar style to the measuring text here if you want to get an accurate measurement.

            textProperty().addListener(observable -> {
                measuringText.setText(getText());
                setPrefWidth(measureTextWidth(measuringText) + MAGIC_PADDING);
            });
        }

        private double measureTextWidth(Text text) {
            text.applyCss();
            return text.getLayoutBounds().getWidth();
        }
    }
}

关于java - 自动扩展 TextField 以适合文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57813131/

相关文章:

java - 应用程序在 android 11 上崩溃 : java. lang.ExceptionInInitializerError

java - 在 OpenGL 2.0+ 中照亮纹理对象

java - 创建动态地与 UI 中的数据对话的 XML

JavaFX - 居中覆盖 BorderPane 的 BackgroundImage

macos - 在 OS X 上以编程方式隐藏(但不退出)应用程序

java - 我们可以在 SWING 代码中使用 JAVAFX 代码吗?

java - 在某些条件下可以使用 Thread.suspend() 吗?

java - 如何确定正确的编码?

java - 如何使用 Bindings.bindContent?

JavaFX:使用 FXML 按行(在网格 Pane 中)组织控件