Search code examples
javafxtextfieldgridpanel

getting the contenents of a GridPane javafx


I have a GridPane in every row there's a Hbox which contain labels and textfields. I want to get the text that the user writes in the textfields and also get the text written in the labels how can I do that?


Solution

  • import javafx.application.Application;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    /**
     *
     * @author reegan
     */
    public class GridPaneStackOverFlow extends Application {
    
        @Override
        public void start(Stage primaryStage) {
    
            GridPane gp = new GridPane();
            gp.add(createNode("Stack"), 0, 0);
            gp.add(createNode("Over"),0,1);
            gp.add(createNode("Flow"), 0, 2);
            StackPane root = new StackPane();
            root.getChildren().add(gp);
    
            Scene scene = new Scene(root, 300, 250);
    
            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
    
        public static void main(String[] args) {
            launch(args);
        }
    
        public HBox createNode(String label) {
            HBox box = new HBox(20);
            final Label l = new Label(label);
            TextField field = new TextField();
            field.textProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> ov, String t, String t1) {
                    System.out.println( l.getText()+ " : " +t);
                }
            });
            box.getChildren().addAll(l,field);
            return box;
    
        }
    
    }