TextArea - Can I get the number of lines?
I was wondering if there is a way to find out how many lines of text there are in a textarea. And also if you can listen to the number of lines. I am trying to develop a component that only displays one line at first, and then starts growing as needed as the number of lines written increases. Let me know if this is not clear enough.
Thanks in advance.
source to share
which displays only one line at first and then starts growing as needed as the number of lines written increases.
just add new line text to TextArea prefixed with new line character \n
textArea.appendText("\n This is new line Text");
Sample code:
for (int i = 1; i < 100; i++) {
textArea.appendText("\n This is Line Number : " +i);
}
Result:
Have I misinterpreted your question?
source to share
To keep track of the number of lines, you can add a listener or binding to TextArea#textProperty
.
To keep track of the height TextArea
, you can add a listener to the subnode boundaries with a styleclass content
that stores the 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 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();
}
source to share