7. FXML

JavaFX Property 是 JavaFX 控件的一个特殊类型的成员变量。JavaFX 属性通常用于包含控件属性,如 JavaFX 控件的 x 和 y 位置、宽度和高度、文本、子属性和其他中心属性。您可以将更改监听附加到 JavaFX 属性,这样当属性值更改时,其他组件可以得到通知,并且您可以将属性绑定到彼此,这样当一个属性值更改时,另一个属性值也会更改。

JavaFX属性的类型

有两种类型的JavaFX属性:

  • 读/写
  • 只读

JavaFX的属性包含实际值,并提供更改支持,无效支持和绑定功能。

所有JavaFX属性类都位于 javafx.beans.property.* 包命名空间中。

下面的列表是常用的属性类。

  • javafx.beans.property.SimpleBooleanProperty
  • javafx.beans.property.ReadOnlyBooleanWrapper
  • javafx.beans.property.SimpleintegerProperty
  • javafx.beans.property.ReadOnlyintegerWrapper
  • javafx.beans.property.SimpleDoubleProperty
  • javafx.beans.property.ReadOnlyDoubleWrapper
  • javafx.beans.property.SimpleStringProperty
  • javafx.beans.property.ReadOnlyStringWrapper

Simple 的属性是读/写属性类。具有 ReadOnly 的属性是只读属性。

读/写属性

读/写属性是可以读取和修改的属性值。

例如, SimpleStringProperty 类创建一个字符串属性,该属性对包装的字符串值是可读写的。

以下代码演示了一个 SimpleStringProperty 类的实例,并通过set()方法修改该属性。

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Main{
  public static void main(String[] args) {
    StringProperty password  = new SimpleStringProperty("w3cschool.cn");
    password.set("example.com");
    System.out.println("Modified StringProperty "  + password.get() );
  }
}

要读取值,请调用 get()方法或 getValue()方法,该方法返回实际的包装值。

要修改该值,请调用 set()方法或 setValue()并传入一个字符串。

只读属性

要创建只读属性,请使用以 ReadOnly 作为前缀的包装类。

创建只读属性需要两个步骤。

  1. 实例化只读包装类
  2. 调用方法getReadOnlyProperty()返回一个真正的只读属性对象
ReadOnlyStringWrapper userName = new ReadOnlyStringWrapper("www.w3cschool.cn"); 
ReadOnlyStringProperty readOnlyUserName  = userName.getReadOnlyProperty();

示例

做一个示例,当输入框的值发生改变的时候,将其实时动态的显示在其Label标签上。

import javafx.application.Application;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class TestProperty extends Application {

	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		FlowPane pane = new FlowPane(Orientation.VERTICAL);
		pane.setPadding(new Insets(10));
		Label label = new Label();
		TextField textField = new TextField();
		
		pane.getChildren().add(label);
		pane.getChildren().add(textField);
		
		StringProperty textProperty = textField.textProperty();
		textProperty.addListener((observableValue, oldVal, newVal)->{
			label.textProperty().setValue(newVal);
		});
		
		Scene scene = new Scene(pane, 800, 700);
		primaryStage.setScene(scene);
	    primaryStage.setTitle("TestProperty");

	    primaryStage.show();
	}
}

图片.png