建立MainClass
使用 IDEA 建立 MainClass
image
package sample;
import javafx.application.Application;
import javafx.stage.Stage;
public class MainApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
}
}
launch Method
要注意的是
- Main 必须继承 Application。
- (1)main 方法中必须,且只能调用一次 launch(args)。(2)launch 方法直到应用结束才会返回。
- launch 会自动调用 start 方法启动应用,并传入 Stage 参数。Stage 可以简单看做 Windows 下的「窗口」。
加载 FXML 文件
首先在 start 方法中,保存 stage,并且加上 title。
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
initRootLayout();
primaryStage.show();
}
之后从 XML 文件中载入 Pane,并且 Set 到 Scene 中去
public void initRootLayout() {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/RootLayout.fxml"));
rootLayout = loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
}
image
建立 Model Class
在JavaFX中,Model Class 的 Field 一般用 property 类型。这个类型里面有监听器,可以方便的实现前后台的数据绑定和同步。
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty street;
private final IntegerProperty postalCode;
private final StringProperty city;
private final ObjectProperty<LocalDate> birthday;
我们需要建立一个,List来保存这些数据,这样的话 Controller 就可以拿到这些数据。最好是 List 这边出现改动,Controller 那边可以同步改动。为了这个需求Java引进了Observable。
private ObservableList<Person> personData = FXCollections.observableArrayList();
建立Controller
按照规定的名称建立一个 Controller Class,并且按照之前提到的在Scene Builder 中将其绑定,这样的话就可以在FXML加载的时候,将这些 Control 填入 Controller Class 的 Field。
可以声明一个initialize()方法,这个方法会在FXML加载时被自动调用。
例如
private void initialize() {
// Initialize the person table with the two columns.
firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
}