Reputation: 928
I was wondering if there's any way to know how many lines of text a textarea has. And also, if it'd be possible to listen for number of lines changes. I'm trying to develop a component which displays just one line at first, and then starts to grow as necessary, as the number of written lines increase. Let me know if it's not clear enough.
Thanks in advance.
Upvotes: 3
Views: 9450
Reputation: 21
Count current rows of textArea:
As a string:
String.valueOf(textArea.getText().split("\n").length);
As a integer:
textArea.getText().split("\n").length;
System.getProperty("line.separator")
can be used instead of "\n"
.
Upvotes: 2
Reputation: 34478
To monitor number of lines you can add listener or binding to TextArea#textProperty
.
To track TextArea
height you can add listener to the bounds of subnode with styleclass content
which stores actual text. See next example:
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();
}
Upvotes: 1
Reputation: 8900
which displays just one line at first, and then starts to grow as necessary, as the number of written lines increase.
just append new Line text to TextArea with prefix new line character \n
textArea.appendText("\n This is new line Text");
Example code :
for (int i = 1; i < 100; i++) {
textArea.appendText("\n This is Line Number : " +i);
}
Result :
am i misinterpreted your question ?
Upvotes: 1