javajavafxtextareachangelistener

JavaFX: Use ChangeListener to dynamically adjust TextArea according to the Scene size/Stage size


I would like to use a ChangeListener to dynamically adjust the size of a TextArea, for example the width. I have created the ChangeListener, but not sure if it is correct, also unable to try due to an error (NullpointerException). This error occures due to the reason that the Stage is not yet initialized (read it on StackOverflow). I have created the listener in the controller class, and put the method adjustTextArea() into the initialize() method.

I would like to aks, where to put my method, and is it a correct way to do it?

This is the method:

// ChangeListener to change width of a textarea
public void adjustTextArea(TextArea textarea){

    // Using a getter to get the primarystage (view is my package, GUI is a class in which I have the getter):
    view.GUI.getpStage().maxWidthProperty().addListener(new ChangeListener<Number>(){

        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
            // To check if it is working:
            System.out.println("Size changed! Original size: "+oldValue.intValue()+", new size: "+ newValue.intValue() + ")\n");
            // Change TextArea size (width):
            textarea.setPrefWidth(newValue.doubleValue());
        }
    });
}

This is how I call my method:

@FXML
    public void initialize(){
adjustTextArea(this.textarea);
}

Solution

  • I solved this issue by adding the ChangeListener after the pStage.show(), so after calling the show() on the prinary stage, in my GUI class.

    pStage.widthProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
                    getController.textarea.setPrefWidth(newValue.doubleValue());
                }
    });