Autosize text area into tabpane in javaFX

假如想象 提交于 2019-12-25 01:56:08

问题


I hava 3 tabs in a TabPane that each one has a text area with different texts and different length. I want to autosize text area according to it's length in each tab. I don't understand what should I do ? using scene builder ? css ?javaFX methods ? Thank's in Advance ...


回答1:


I think you are asking that the text areas grow or shrink according to the text that is displayed in them?

If so, see if this code helps:

import java.util.concurrent.Callable;

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 AutosizingTextArea extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextArea textArea = new TextArea();
        textArea.setMinHeight(24);
        textArea.setWrapText(true);
        VBox root = new VBox(textArea);
        Scene scene = new Scene(root, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();

        // This code can only be executed after the window is shown:

        // Perform a lookup for an element with a css class of "text"
        // This will give the Node that actually renders the text inside the
        // TextArea
        Node text = textArea.lookup(".text");
        // Bind the preferred height of the text area to the actual height of the text
        // This will make the text area the height of the text, plus some padding
        // of 20 pixels, as long as that height is between the text area's minHeight
        // and maxHeight. The minHeight we set to 24 pixels, the max height will be
        // the height of its parent (usually).
        textArea.prefHeightProperty().bind(Bindings.createDoubleBinding(new Callable<Double>(){
            @Override
            public Double call() throws Exception {
                return text.getBoundsInLocal().getHeight();
            }
        }, text.boundsInLocalProperty()).add(20));

    }

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

If you want to make this reusable, then you could consider subclassing TextArea. (In general, I dislike subclassing control classes.) The tricky part here would be to execute the code that makes the TextArea expand once it has been added to a live scene graph (this is necessary for the lookup to work). One way to do this (which is a bit of a hack, imho) is to use an AnimationTimer to do the lookup, which you can stop once the lookup is successful. I mocked this up here.



来源:https://stackoverflow.com/questions/22732766/autosize-text-area-into-tabpane-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!