TableView的数据绑定需要一个类型绑定
类里面必须有property
Student类(需要导入的类)
package sample;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Student {
private SimpleStringProperty name=new SimpleStringProperty();
private SimpleStringProperty id=new SimpleStringProperty();
public Student(String name,String id)
{
setName(name);
setId(id);
}
public String getName()
{
return name.get();
}
public SimpleStringProperty nameProperty()
{
return name;
}
public void setName(String name)
{
this.name.set(name);
}
public String getId()
{
return id.get();
}
public void setId(String id)
{
this.id.set(id);
}
public SimpleStringProperty idProperty()
{
return id;
}
}
Controller类
package sample;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class Controller {
@FXML
private TableView<Student> personTable;
@FXML
private TableColumn<Student, String> nameCol;
@FXML
private TableColumn<Student, String> idCol;
private ObservableList<Student> personData= FXCollections.observableArrayList();
@FXML
private void initialize()
{
idCol.setCellValueFactory(cellData->cellData.getValue().idProperty());
nameCol.setCellValueFactory(cellData->cellData.getValue().nameProperty());
personTable.setItems(personData);
personData.add(new Student("A","01"));
}
}
FXML类
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<TableView fx:id="personTable" layoutX="86.0" layoutY="85.0" prefHeight="200.0" prefWidth="365.0">
<columns>
<TableColumn fx:id="nameCol" prefWidth="75.0" text="name" />
<TableColumn fx:id="idCol" prefWidth="75.0" text="id" />
</columns></TableView>
</children>
</AnchorPane>