JavaFX 2 TextArea根据其内容更改高度 [英] JavaFX 2 TextArea that changes height depending on its contents

查看:144
本文介绍了JavaFX 2 TextArea根据其内容更改高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaFX 2.2中,有没有办法让TextArea(使用setWrapText(true)和常量maxWidth)根据内容改变其高度?

In JavaFX 2.2, is there any way to make TextArea (with setWrapText(true) and constant maxWidth) change its height depending on contents?

理想的行为:当用户在TextArea中输入内容时,它会在需要另一行时调整大小,并在不再需要该行时减少。

The desired behaviour: while user is typing something inside the TextArea it resizes when another line is needed and decreases when the line is needed no more.

或者是否有更好的JavaFX控件可以在这种情况下使用?

Or is there a better JavaFX control that could be used in this situation?

推荐答案

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

You can bind the prefHeight of the text area to the height of the text it contains. This is a bit of a hack, because you need a lookup to get the text contained in the text area, but it seems to work. You need to ensure that you lookup the text node after CSS has been applied. (Typically this means after it has appeared on the screen...)

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根据其内容更改高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆