How to set text of a TextArea in JavaFX from constructor?


Question

I want to set a text in a TextArea from start in JavaFX, i use this code in constructor:

public class Myclass implements Initializable{
    @FXML TextArea txta;
    @FXML Button btn;
    String msg;
    Myclass(){
        msg="Hello World";
        txta.setText(msg);//This line is my setter.
    }
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                msg=msg+"\nHallo Again!!");
                txta.setText(msg);
            }
        });
    }

Then the FXML doesn't show, but when i make comment the setter line, the FXML shows normally. Please help, How can i fix this problem?

1
0
11/5/2014 8:17:36 AM

Accepted Answer

Your class is a controller, and it doesn't need a constructor. All the initial settings can be done in the initialize method. You can find here a basic tutorial.

Your text area txta will be properly initialized (that's why it has a @FXML annotation), so this will be enough:

public class Myclass implements Initializable{

    @FXML private TextArea txta;
    @FXML private Button btn;
    private String msg;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        msg="Hello World";
        txta.setText(msg);

        btn.setOnAction(e->{
            msg=msg+"\nHallo Again!!";
            txta.setText(msg);
        });
    }
}
1
11/5/2014 10:00:47 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon