0

I'm still a noob in JavaFX, I can print the content of the table that I query, the problem is that I want the content to be placed inside the tableview. This is the code that I have done.

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;        
}

}

Please help me.

1 Answers1

-1

I would make a defaultTableModel class which I would then use to populate the table. The advantage of doing so will also allow you to use the same class to populate all possible future tables as well. Here is one I have used in the past:

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;
    }
}

Then just on the method that creates the table, you initialize all needed components:

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();
 }

You can also then set the names of the columns within the table if you need, by altering the SQL sentence "SELECT (nameOfColumn) AS (newNameOfColumn) since this table model that I provided here gets the column names DIRECTLY from the database tables column names. Hope this helps.

ghoulfolk
  • 326
  • 7
  • 17
  • I already have a table with columns that I created in the FXML file. But I will explore your sample code. – Christopher Gerra Jun 27 '13 at 11:08
  • alright, I noticed I forgot the statement and execution so i edited them in :) – ghoulfolk Jun 27 '13 at 11:14
  • thanks for the quick reply @ghoulfolk, I will apply it. – Christopher Gerra Jun 27 '13 at 11:29
  • Consider to use try-with-resources to close your connection etc. – Puce Jun 27 '13 at 11:33
  • Hello, .setModel method is not found. What do i need to import? – Christopher Gerra Jul 01 '13 at 03:19
  • in the public class DefTableModel make sure you have imported javax.swing.table.DefaultTableModel; It should find the tableName.setModel(DefTableModel.buildTableModel(rs)); after this, it is a default method of JTable class. – ghoulfolk Jul 01 '13 at 10:40
  • I think I found the problem: the setModel() is a method of JTable, and since you are using this TableViewer (which does not directly have this method) it cannot be called directly. I got 2 proposals. First would be to try: tblViewer.getTable.setModel(DefTableModel.buildTableModel(rs)); IF this does not work, I would think you might need to change the table viewer directly to a JTable element.. but then you would not have the viewer at all. – ghoulfolk Jul 01 '13 at 10:49