var myText = "This is the text of my label.";
...
Controllers
fx:controller
public class MyController {
public void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
}
} 当然Controllers类还可以实现Initializable接口,以便在被加载时可以调用初始化方法initialize()
package com.foo;
public class MyController implements Initializable {
public Button button;
@Override
public void initialize(URL location, Resources resources)
button.setOnAction(new EventHandler
() {
@Override
public void handle(ActionEvent event) {
System.out.println("You clicked me!");
}
前面介绍的都是通过public修饰field与方法,但是这破坏了封装性原则。 由于controller是对FXML Loader可见的,所以没必要对外部开放访问权限。 这样我们就必须通过@FXML注解进行修饰。
public class MyController {
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
}
}
public class MyController implements Initializable {
@FXML private Button button;
@FXML
protected void initialize()
button.setOnAction(new EventHandler
() {
@Override
public void handle(ActionEvent event) {
System.out.println("You clicked me!");
}
Nested Controllers嵌套的控制器访问。
FXMLLoader
URL location = getClass().getResource("example.fxml");
ResourceBundle resources = ResourceBundle.getBundle("com.foo.example");
FXMLLoader fxmlLoader = new FXMLLoader(location, resources);
Pane root = (Pane)fxmlLoader.load();
MyController controller = (MyController)fxmlLoader.getController();
使用FXML结合FXMLLoader自定义UI组件
通过使用
自定义的UI组件:
package fxml;
import java.io.IOException;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
public class CustomControl extends VBox {
@FXML private TextField textField;
public CustomControl() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public String getText() {
return textProperty().get();
}
public void setText(String value) {
textProperty().set(value);
}
public StringProperty textProperty() {
return textField.textProperty();
}
@FXML
protected void doSomething() {
System.out.println("The button was clicked!");
}
}
使用自定义的UI组件:
HBox hbox = new HBox();
CustomControl customControl = new CustomControl();
customControl.setText("Hello World!");
hbox.getChildren().add(customControl);