I'm learning the binding concept in Java FX. I have a Person class which has firstName and lastName which are of type SimpleStringProperty. In my FXML, I have two text fields, and a label. When the user enters the First Name and last Name, I need to display that in the Label as Full Name.
I'm getting NullPointerException when trying person.get().firstNameProperty(). How do I implement this sample requirement?
public class CustomControl extends Pane{
@FXML
private TextField firstNameTextField, lastNameTextField;
@FXML
private Label fullNameLabel;
private ObjectProperty<Person> person = new SimpleObjectProperty<Person>( this, "person" );
public CustomControl(){
try{
FXMLLoader loader = new FXMLLoader( this.getClass().getResource( "EnterDetails.fxml" ) );
loader.setController( this );
loader.load();
registerListeners();
}
catch( IOException e ){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*/
private void registerListeners(){
firstNameTextField.textProperty().bind( person.get().firstNameProperty() );
lastNameTextField.textProperty().bind( person.get().lastNameProperty() );
fullNameLabel.textProperty().bind( Bindings.concat( person.get().firstNameProperty() ).concat( person.get().lastNameProperty() ) );
}
public ObjectProperty<Person> personProperty(){
return person;
}
public Person getPerson(){
return personProperty().get();
}
public void setPerson( Person person ){
personProperty().set( person );
}
}
Below is the Person class
public class Person{
private SimpleStringProperty firstName=new SimpleStringProperty();
private SimpleStringProperty lastName=new SimpleStringProperty();
public String getFirstName(){
return firstNameProperty().get();
}
public void setFirstName( String firstName ){
firstNameProperty().set( firstName );
}
public SimpleStringProperty firstNameProperty(){
return firstName;
}
public String getLastName(){
return lastNameProperty().get();
}
public void setLastName( String lastName ){
lastNameProperty().set( lastName );
}
public SimpleStringProperty lastNameProperty(){
return lastName;
}
}
This is the FXML page
<GridPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" />
<RowConstraints minHeight="10.0" prefHeight="30.0" />
<RowConstraints minHeight="10.0" prefHeight="30.0" />
</rowConstraints>
<columnConstraints>
<ColumnConstraints minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<children>
<Label text="FirstName" />
<Label text="Last Name" GridPane.rowIndex="1" />
<TextField fx:id="firstNameTextField" GridPane.columnIndex="1" />
<TextField fx:id="lastNameTextField" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Label fx:id="fullNameLabel" GridPane.rowIndex="2" />
</children>
</GridPane>