首先你需要持有該表的信息模型類的,讓我們稱此爲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