使用JavaFX中的数据库填充tableview
我开始学习javaFX,我需要使用数据库中的数据填充表。 我在线阅读了很多代码,但我还没找到我想要的东西。 我读了这个,但我不知道如何实现最后一个function。 我读了一些其他代码来做到这一点,到目前为止这是我的一些代码:
@FXML private TableView table; @FXML private TableColumn nameCol; @FXML private TableColumn emailCol; private ObservableList data; public void initialize(URL location, ResourceBundle resources) { nameCol.setCellValueFactory(new PropertyValueFactory(“name”)); emailCol.setCellValueFactory(new PropertyValueFactory(“email”)); buildData(); } public void buildData() { Connection connect = new Connection(); Statement st = connect.Connect(); data = FXCollections.observableArrayList(); try { ResultSet rs = st.executeQuery("SELECT * FROM USER"); while (rs.next()) { ObservableList row = FXCollections.observableArrayList(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { row.add(rs.getString(i)); System.out.println(row); } data.add(pol); } tabla.setItems(data); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } }
我希望你可以帮助我
我相信这会对你有所帮助:
public class DBClass{ public Connection getConnection() throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql://192.168.0.1:3306/dbname","mysqluser","mysqluserpwd"); } }
在Controller类中,执行以下操作:
@FXML void initialize(){ assert tableview != null : "fx:id=\"tableview\" was not injected: check your FXML file 'UserMaster.fxml'."; colUserName.setCellValueFactory( new PropertyValueFactory("userName")); colPassword.setCellValueFactory( new PropertyValueFactory("userPassword")); colUserType.setCellValueFactory( new PropertyValueFactory("userType")); colPhoto.setCellValueFactory( new PropertyValueFactory
并为每个要使用TableView操作的实体(表)创建一个单独的java文件POJO
public class Usermaster{ public SimpleIntegerProperty userId = new SimpleIntegerProperty(); public ObjectProperty userPhoto = new SimpleObjectProperty(); public SimpleStringProperty userName = new SimpleStringProperty(); public SimpleStringProperty userPassword = new SimpleStringProperty(); public SimpleStringProperty userType = new SimpleStringProperty(); public SimpleStringProperty encPass = new SimpleStringProperty(); public SimpleStringProperty updt = new SimpleStringProperty(); public SimpleStringProperty uptm = new SimpleStringProperty(); public Integer getUserId() { return userId.get(); } public Object getUserPhoto() { return userPhoto.get(); } public String getUserName() { return userName.get(); } public String getUserPassword() { return userPassword.get(); } public String getUserType() { return userType.get(); } public String getEncPass() { return encPass.get(); } public String getUpdt() { return updt.get(); } public String getUptm() { return uptm.get(); } }
我已经测试了这个程序,它运行得很好。