JavaFX 2 TextArea 根据其内容改变高度

标签 java javafx javafx-2

在 JavaFX 2.2 中,是否有任何方法可以使 TextArea(使用 setWrapText(true) 和常量 maxWidth)根据内容改变其高度?

期望的行为:当用户在 TextArea 中输入内容时,它会在需要另一行时调整大小,而在不再需要该行时缩小。

或者是否有更好的 JavaFX 控件可用于这种情况?

最佳答案

您可以将文本区域的 prefHeight 绑定(bind)到它包含的文本的高度。这有点 hack,因为您需要 lookup 来获取文本区域中包含的文本,但它似乎可以工作。您需要确保在应用 CSS 后查找 text 节点。 (通常这意味着它出现在屏幕上之后...)

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ResizingTextArea extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextArea textArea = new TextArea();
        textArea.setWrapText(true);

        textArea.sceneProperty().addListener(new ChangeListener<Scene>() {
            @Override
            public void changed(ObservableValue<? extends Scene> obs, Scene oldScene, Scene newScene) {
                if (newScene != null) {
                    textArea.applyCSS();
                    Node text = textArea.lookup(".text");
                    textArea.prefHeightProperty().bind(Bindings.createDoubleBinding(new Callable<Double>() {
                        @Override
                        public Double call() {
                            return 2+text.getBoundsInLocal().getHeight();
                        }
                    }), text.boundsInLocalProperty()));
                }
            }
        });

        VBox root = new VBox(textArea);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

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

关于JavaFX 2 TextArea 根据其内容改变高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30217429/

相关文章:

java - 如何在使用 css 样式表的 eclipse 中 jar javafx 应用程序

java - 应用程序启动方法java.lang.reflect.InvocationTargetException中的异常

java - 有没有更好的方法来测试以下方法而无需模拟返回模拟?

Java - 围绕特定点缩放 Canvas

java - 服务器中止与 android 应用程序的连接 : An established connection was aborted by the software in your host machine

JavaFX:如何管理边框中的焦点遍历

javafx - fxml:如何处理 Controller 中的按钮操作?

java - 从 JavaFX 插入 MySQL

java - Controller "classname"没有事件槽 "methodname"

java - 多个 JavaFX 组件集成到一个阶段