2013-01-31 38 views
3

我想知道是否有任何方法知道文本區有多少行文本。而且,如果可以聽取更改的行數。我試圖開發一個組件,它首先只顯示一行,然後隨着寫入行數的增加而開始增長。 讓我知道如果它不夠清楚。TextArea - 是否可以獲取行數?

在此先感謝。

回答

1

它首先顯示一行,然後隨着寫入行數的增加而開始增長,因爲必須增加 。

只是新行文本追加到文本區前綴的新行字符\n

textArea.appendText("\n This is new line Text"); 

示例代碼:

for (int i = 1; i < 100; i++) { 
      textArea.appendText("\n This is Line Number : " +i); 
     } 

結果:

enter image description here

我誤解了你的問題?

+0

是的,我正在那樣做。事情是,我希望textarea只有一行,然後增長。但不僅當我追加\ n(我有一個事件處理程序的Shift + Enter),而且當textarea包裝文本到一個新的行。我在這裏問了https://forums.oracle.com/forums/thread.jspa?threadID=2493391&tstart=0 而現在看來,目前還沒有辦法做到這一點。我在javafx jira上提交了一個RFE。 – alscu

0

要監視可以添加偵聽器或綁定到TextArea#textProperty的行數。

要跟蹤TextArea高度,您可以添加偵聽器到子節點的邊界,樣式爲content,其中存儲實際文本。見下面的例子:文本的

public void start(Stage primaryStage) { 
    final TextArea txt = new TextArea("hi"); 

    // find subnode with styleclass content and add a listener to it's bounds 
    txt.lookup(".content").boundsInLocalProperty().addListener(new ChangeListener<Bounds>() { 
     @Override 
     public void changed(ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) { 
      txt.setPrefHeight(t1.getHeight()); 
     } 
    }); 

    Button btn = new Button("Add"); 
    btn.setOnAction(new EventHandler<ActionEvent>() { 
     @Override 
     public void handle(ActionEvent event) { 
      txt.setText(txt.getText() + "\n new line"); 
     } 
    }); 

    VBox root = new VBox(); 
    root.getChildren().addAll(btn, txt); 

    primaryStage.setScene(new Scene(root, 300, 250)); 
    primaryStage.show(); 
} 
+0

txt.lookup(「。content」)返回null(Java 8 Update 66)。該解決方案不起作用。 – Rolch2015

2

計數當前行:

作爲字符串:

String.valueOf(textArea.getText().split("\n").length); 

作爲整數:

textArea.getText().split("\n").length; 

System.getProperty("line.separator")可以用來代替的"\n"

+0

包裝文字時不起作用 – Rolch2015

相關問題