簡體   English   中英

在JavaFX中將文本區域自動調整為Tabpane

[英]Autosize text area into tabpane in javaFX

我在TabPane中擁有3個標簽,每個標簽都有一個帶有不同文本和不同長度的文本區域。 我想根據每個選項卡中的長度自動調整文本區域的大小。 我不知道該怎么辦? 使用場景生成器? CSS?javaFX方法? 提前致謝 ...

我認為您是在要求文本區域根據顯示在其中的文本是增長還是縮小?

如果是這樣,請查看此代碼是否有幫助:

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);
    }
}

如果您想使其可重用,則可以考慮將TextArea子類化。 (通常,我不喜歡對控件類進行子類化。)這里最棘手的部分是一旦將TextArea添加到實時場景圖中,便執行使TextArea擴展的代碼(這對於查找工作是必需的)。 一種執行此操作的方法(有點小技巧,恕我直言)是使用AnimationTimer進行查找,一旦查找成功,您就可以停止查找。 在這里嘲笑了這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM