使用MySQL数据库在JavaFX中填充TableView

时间:2013-06-27 10:20:56

标签: java javafx tableview populate

我仍然是JavaFX中的菜鸟,我可以打印我查询的表的内容,问题是我希望将内容放在tableview中。这是我所做的代码。

public class TableViewController  implements Initializable{


@FXML
private TableView<studentInfo> tblViewer = new TableView();
@FXML
private TableColumn colID = new TableColumn();
@FXML
private TableColumn colName = new TableColumn();
@FXML
private TableColumn colAddress = new TableColumn();
@FXML
private TableColumn colAge = new TableColumn();
@FXML
private TableColumn colContact = new TableColumn();
@FXML
private Button cmdTest;

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
    System.out.println("READ");
    System.out.println(this.getClass().getSimpleName() + ".initialize"); 
    cmdTest.setOnAction(new EventHandler<ActionEvent>() {            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Button Pressed");

                colID.setCellValueFactory(new PropertyValueFactory<studentInfo, Integer>("id"));
                colName.setCellValueFactory(new PropertyValueFactory<studentInfo, String>("name"));
                colAddress.setCellValueFactory(new PropertyValueFactory<studentInfo, String>("address"));
                colAge.setCellValueFactory(new PropertyValueFactory<studentInfo, Integer>("age"));
                colContact.setCellValueFactory(new PropertyValueFactory<studentInfo, String>("contact_num"));
                tblViewer.getItems().setAll(getAllstudentInfo());
            }
        } );       
}

public class studentInfo{

    private final SimpleIntegerProperty idCol;
    private final SimpleStringProperty nameCol;
    private final SimpleStringProperty addressCol;
    private final SimpleIntegerProperty ageCol;
    private final SimpleStringProperty contact_numCol;

    public studentInfo(Integer id, String name, String address, Integer age, String contact_num){
        this.idCol = new SimpleIntegerProperty(id);
        this.nameCol = new SimpleStringProperty(name);
        this.addressCol = new SimpleStringProperty(address);
        this.ageCol = new SimpleIntegerProperty(age);
        this.contact_numCol = new SimpleStringProperty(contact_num);
      }  
      public Integer getidCol(){
          return idCol.get();
      }
      public void setidCol(Integer id){
          idCol.set(id);      
      }
      public String getnameCol(){
          return nameCol.get();
      }
      public void setnameCol(String name){
          nameCol.set(name);
      }
      public String getaddressCol(){
          return addressCol.get();
      }
      public void setaddressCol(String address){
          addressCol.set(address);
      }
      public Integer getageCol(){
          return ageCol.get();
      }
      public void setageCol(Integer age){
          ageCol.set(age);
      }
      public String getcontact_numCol(){
          return contact_numCol.get();
      }
      public void setcontact_numCol(String contact_num){
          contact_numCol.set(contact_num);
      }        
}

//public static ObservableList<COA> getAllCOA(){
public List<studentInfo> getAllstudentInfo(){
    Connection conn;
    List ll = new LinkedList();
    Statement st;
    ResultSet rs;
    String url = "jdbc:mysql://localhost/java_test";
    String user = "root";
    String pass = "";
    String driver = "com.mysql.jdbc.Driver";

    try{
        Class.forName(driver);
        conn = DriverManager.getConnection(url, user, pass);
        st = conn.createStatement();
        String recordQuery = ("Select * from student");            
        rs = st.executeQuery(recordQuery);
        while(rs.next()){                
            Integer id = rs.getInt("id");
            String name = rs.getString("name");
            String address = rs.getString("address");
            Integer age = rs.getInt("age");
            String contact_num = rs.getString("contact_num");

            ll.add(new studentInfo(id, name, address, age, contact_num));
            System.out.println(id +","+ name +","+ address +","+ age +","+ contact_num +" "+"added.");
        }            
    }catch(ClassNotFoundException | SQLException ex){
        Logger.getLogger(TableViewController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ll;        
}

}

请帮帮我。

1 个答案:

答案 0 :(得分:-1)

我会创建一个defaultTableModel类,然后我将用它来填充表。这样做的优点还允许您使用相同的类来填充所有可能的未来表。 这是我过去使用的一个:

public class DefTableModel {
static DefaultTableModel buildTableModel(ResultSet rs)throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }
    DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };              
    return  tableModel;
    }
}

然后,只需创建表的方法,就可以初始化所有需要的组件:

public void methodNameHere(){
 PreparedStatement searchParameter=null;
 ResultSet rs=null;
 ConnectionClass connServer = new ConnectionClass();
 Connection conn=connServer.databaseConnect();
 try{
   searchParameter=conn.prepareStatement("SELECT * FROM student");
   rs = searchParameter.executeQuery(); 
    if(!rs.isBeforeFirst()){

    rs.close();
    searchParameter.close();  //dont forget to close all if nothing is found
    conn.close();
   }
  else{
     tableName.setModel(DefTableModel.buildTableModel(rs));
  }
 catch (SQLException e){
   //do something if you get an sql exception
 }
 catch (Exception e2){
  //do something incase of any other exception
 }
 finally {
     rs.close();
 searchParameter.close();  //dont forget to close all when done.
 conn.close();
 }

如果需要,您还可以通过更改SQL语句“SELECT(nameOfColumn)AS(newNameOfColumn)”来设置表中列的名称,因为我在此提供的表模型直接从数据库中获取列名表列名称。希望这有帮助。