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?
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);
});
}
}