首先你需要持有该表的信息模型类的,让我们称此为PatientModel
,看起来像这样:
public class PatientModel {
private StringProperty pid;
private StringProperty patientName;
private StringProperty address;
/* ...
* and so on...
*/
public PatientModel(String pid, String patientName, String address) {
this.pid = new SimpleStringProperty(pid);
this.patientName = new SimpleStringProperty(patientName);
this.address = new SimpleStringProperty(address);
}
public String getPid() {
return pid.get();
}
public StringProperty pidProperty() {
return pid;
}
public String getPatientName() {
return patientName.get();
}
public StringProperty patientNameProperty() {
return patientName;
}
public String getAddress() {
return address.get();
}
public StringProperty addressProperty() {
return address;
}
}
然后,你需要一个.fxml
文件与此类似:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.91"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="stackoverflow.TestController">
<TableView fx:id="table">
<columns>
<TableColumn fx:id="pidColumn" text="PID"/>
<TableColumn fx:id="nameColumn" text="Patient Name"/>
<TableColumn fx:id="addressColumn" text="Address"/>
<!-- and so on... -->
</columns>
</TableView>
</AnchorPane>
然后,控制器类:
public class TestController implements Initializable {
@FXML
private TableView<PatientModel> table;
@FXML
private TableColumn<PatientModel, String> pidColumn;
@FXML
private TableColumn<PatientModel, String> nameColumn;
@FXML
private TableColumn<PatientModel, String> addressColumn;
private ObservableList<PatientModel> tableData = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
initTable();
// if the data is coming from an other class you have probably a list of them,
// if not you can simply populate the tableData
List<PatientDto> dtosFromDB = new ArrayList<>();
tableData.addAll(dtosFromDB.stream().map(this::convertDtoToModel).collect(Collectors.toList()));
}
private void initTable() {
table.setItems(tableData);
pidColumn.setCellValueFactory(data -> data.getValue().pidProperty()); // here is where tha magic happens :)
nameColumn.setCellValueFactory(data -> data.getValue().patientNameProperty()); // this sets the cells value from
// the model.
addressColumn.setCellValueFactory(data -> data.getValue().addressProperty());
}
private PatientModel convertDtoToModel(PatientDto dto) {
return new PatientModel(dto.getPid().toString(), dto.getName(), dto.getAddress()/* and so on */);
}
}
完成这些课程之后,您可以简单地从主课程中加载.fxml
,然后您必须完成所有信息并且它应该可以工作。
P.S.对于缩进不好意思,我不能在这里按行缩进整个代码,它太无聊了。
我也有一个sql date从datepicker中获得,我如何在Stringproperty中绑定日期? – Manoj
你是否认为这个List dtosfromDB保存了数据库中的所有数据? – Manoj
据我所知javafx没有内置的DatePickerTableCell,但你可以写一个。这是一个映射的东西,你必须编写一些转换器方法/类,然后你可以随意使用它。 – Sunflame