2014-03-29 30 views
0

我在TabPane中有3個選項卡,每個選項卡都有一個帶有不同文本和不同長度的文本區域。 我想根據每個標籤中的長度來自動調整文本區域的大小。 我不明白我該怎麼辦?使用場景生成器? css?javaFX方法? 感謝您的提前...在javaFX中將文本區域自動調整爲tabpane

+0

這裏是一個示例: https://stackoverflow.com/questions/44141172/javafx-expandable-textfield-sample – kamirru

回答

4

我認爲您要求文本區域根據顯示的文本增長或縮小?

如果是這樣,看看這個代碼可以幫助:

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。一種方法可以做到這一點(這是一個黑客,imho)是使用AnimationTimer做查找,一旦查找成功,您可以停止查找。我嘲笑了這個here

+0

你能解釋更多的代碼嗎?我想將它用於具有多個選項卡的選項卡窗格,每個選項卡都有一個特殊文本。 – faraa

+0

只需爲每個TextArea做同樣的事情。我將在代碼中添加一些註釋,但您可以只查看我調用的方法的[javadocs](http://docs.oracle.com/javase/8/javafx/api/)。 –

+0

是的,我明白了。謝謝。但是沒有辦法一次做到這一點?例如,如果我有10個標籤,我應該做10次。是否有更好的方法? – faraa