假设您有以下“JavaFX-Bean”:
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Employee {
private final StringProperty lastname = new SimpleStringProperty();
private final StringProperty firstname = new SimpleStringProperty();
private final DoubleProperty salary = new SimpleDoubleProperty();
/**
* @return the lastname Property
*/
public StringProperty lastnameProperty() {
return lastname;
}
/**
* @return the lastname String
*/
public String getLastname() {
return lastname.get();
}
/**
* @param lastname the lastname to set
*/
public void setLastname(final String lastname) {
this.lastname.set(lastname);
}
/**
* @return the firstname property
*/
public StringProperty firstnameProperty() {
return firstname;
}
/**
* @return the firstname String
*/
public String getFirstname() {
return firstname.get();
}
/**
* @param firstname the firstname to set
*/
public void setFirstname(final String firstname) {
this.firstname.set(firstname);
}
/**
* @return the salary Property
*/
public DoubleProperty salaryProperty() {
return salary;
}
/**
* @return the salary double
*/
public double getSalary() {
return salary.get();
}
/**
* @param salary the salary to set
*/
public void setSalary(final double salary) {
this.salary.set(salary);
}
}
现在在应用程序的启动方法中定义一个标签:
Label labaelSalary = new Label();
并将其与'JavaFX-Bean'的salaryProperty绑定:
labaelSalary.textProperty()
.bind(emp.salaryProperty().asString("%.2f"));
添加一个按钮并设置此按钮的操作:
Button changeSalaryButton = new Button("Change Salary");
changeSalaryButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(final ActionEvent event) {
double salary = Math.random() * 10000;
emp.setSalary(salary);
}
});
每次点击 Button 时,Employee 对象 emp 的薪水是随机设置的。labelSalary 的有界文本(属性)立即更改为显示emp Employee 对象的salary 属性的新值。下面是启动方法的代码:
@覆盖
public void start(final Stage primaryStage) {
Employee emp = new Employee();
emp.setFirstname("Fred");
emp.setLastname("Las Frite");
emp.setSalary(12.500);
Label labelSalary = new Label();
labelSalary.textProperty()
.bind(emp.salaryProperty().asString("%.2f"));
Button changeSalaryButton = new Button("OK");
changeSalaryButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(final ActionEvent event) {
double salary = Math.random() * 10000;
emp.setSalary(salary);
}
});
HBox hBox = new HBox(10, labelSalary, changeSalaryButton);
hBox.setPadding(new Insets(20));
hBox.setAlignment(Pos.CENTER);
primaryStage.setScene(new Scene(hBox));
primaryStage.setWidth(400);
primaryStage.setHeight(600);
primaryStage.show();
}