Apsixos
Apsixos

Reputation: 13

I want to populate a jtable using a method (with a query exec) that is defined at another class

I have a jtable "clientTable" in the clientRecorderUI JFrame(extends JFrame)..I also have a class called databaseHandler (public class that extends clientRecorderUI) that i want to use as a controller/model (MVC-esque kinda design). The method in the databaseHandler is called populateTable(an sql that fills the table with the database values).

I also created for testing the same method in the clientRecorderUI to see if the code is sound and it works like a charm(hence the populateTable(); in comments)

How to properly call a method from another class and utilize its graphic components? I am working on NetBeans btw.

Thank you in advance !

This is how i call the method on windowActivated :

private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
    databaseHandler tester=new databaseHandler();
    tester.populateTable(); // TODO add your handling code here:
    //populateTable();

}       

and this is the method in databaseHandler :

  protected void populateTable(){

       String query="Select * from clienttable";
       try {  

           //Call connectDB method to connect to database
           Connection dbCon=mySqlConnection.ConnectDB();

           //Prepare the query
           PreparedStatement pst=dbCon.prepareStatement(query);

           //return ResultSet
           ResultSet rs=pst.executeQuery(query);
           clientTable.setModel(DbUtils.resultSetToTableModel(rs));


       } catch (SQLException ex) {
           Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
       }


   }

Upvotes: 0

Views: 117

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

Make populateTable return a TableModel

protected TableModel populateTable(){

   TableModel model = null;
   String query="Select * from clienttable";
   try {  

       //Call connectDB method to connect to database
       Connection dbCon=mySqlConnection.ConnectDB();

       //Prepare the query
       PreparedStatement pst=dbCon.prepareStatement(query);

       //return ResultSet
       ResultSet rs=pst.executeQuery(query);
       model = DbUtils.resultSetToTableModel(rs);


   } catch (SQLException ex) {
       Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
   }

   return model;
}

Then when you call it, just apply it what ever instance of JTable you have

private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
    databaseHandler tester=new databaseHandler();
    TableModel model = tester.populateTable();
    // Apply it do what ever JTable you have
}   

Upvotes: 2

Related Questions