步骤
0. 项目结构
1. 定义数据模型
2. FXML
3. Controller
4. Stage
5. 效果展示
项目结构
定义数据模型
public class Person {
private StringProperty name;
private IntegerProperty id;
public Person(String name, Integer id) {
this.name = new SimpleStringProperty(name);
this.id = new SimpleIntegerProperty(id);
}
public Integer getId() {
return this.id.get();
}
public String getName() {
return this.name.get();
}
public void setId(Integer id) {
this.id.set(id);
}
public void setName(String name) {
this.name.set(name);
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0"
prefWidth="600.0" style="-fx-background-color: bisque;" xmlns="http://javafx.com/javafx/10.0.2-internal"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="tech.zger.controller.MainController">
<children>
<TableView fx:id="tableView" layoutX="182.0" layoutY="120.0" prefHeight="200.0" prefWidth="200.0">
<columns>
<TableColumn fx:id="tcName" prefWidth="103.20001220703125" text="姓名"/>
<TableColumn fx:id="tcId" prefWidth="96.0" text="学号"/>
</columns>
</TableView>
</children>
</Pane>
Controller
public class MainController implements Initializable {
@FXML
private TableView<Person> tableView;
@FXML
private TableColumn<Person, String> tcName;
@FXML
private TableColumn<Person, Integer> tcId;
@Override
public void initialize(URL location, ResourceBundle resources) {
ObservableList<Person> data = FXCollections.observableArrayList();
data.addAll(
new Person("zg", 1),
new Person("zz", 2),
new Person("zc", 3),
new Person("zx", 4)
);
// 对应Person的各个属性
tcId.setCellValueFactory(new PropertyValueFactory<>("id"));
tcName.setCellValueFactory(new PropertyValueFactory<>("name"));
tableView.setItems(data);
}
}
Stage
public class MainApplication extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/view/main.fxml"));
Scene scene = new Scene(pane, 600, 400);
primaryStage.setScene(scene);
primaryStage.setTitle("TableView");
// 设置图标
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/logo/zg.jpg")));
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}