JavaFX 8 count rows in “textarea”

前端 未结 3 2217
醉话见心
醉话见心 2021-01-26 13:48

We are trying to count the number of rows in a TextArea
Here are the TextArea properties PrefWidth 600 and PrefHeight 620 with MaxHeight 620
Wrap Text is set to true. We

3条回答
  •  日久生厌
    2021-01-26 14:03

    A Minimal, Reproducible Example is something that can be copied and run without much changes, should also have self explanatory variables.

    For your reference, I am providing a demo and can you please update it as per your requirment. It is very hard to follow your code as the variables are not explanatory.

    import javafx.application.Application;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextArea;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.Priority;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class TextAreaLinesCount_Demo extends Application {
        @Override
        public void start(Stage stage) throws Exception {
            final VBox root = new VBox();
            root.setSpacing(10);
            root.setPadding(new Insets(10));
            final Scene sc = new Scene(root, 350, 200);
            stage.setScene(sc);
            stage.show();
    
            Label lines = new Label();
            Label alert = new Label();
            GridPane gp = new GridPane();
            gp.setHgap(10);
            gp.setVgap(10);
            gp.addRow(0, new Label("No of Lines:"), lines);
            gp.addRow(1, new Label("Alert:"), alert);
    
            TextArea textArea = new TextArea();
            textArea.setWrapText(true);
            textArea.textProperty().addListener((obs, old, text) -> {
                lines.setText(text.split("\n").length + "");
                validate(text, alert);
            });
            VBox.setVgrow(textArea, Priority.ALWAYS);
            root.getChildren().addAll(gp, textArea);
    
            textArea.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
        }
    
        private void validate(String text, Label alert) {
            // Can you add your logic here.. and update the "alert" label for when to show the alert
        }
    }
    

提交回复
热议问题