martin doherty
martin doherty

Reputation: 27

JTable is not being populated with the data being pulled from a database

Firstly I have a database connection which is set up and works, now the problem- I have a search button which has an actionlistener connected and when it is clicked it is supposed to populate a JTable but the table is not being populated and I can't figure out why! Below shows a snippet of my connection and the code that tries to populate the table.

public void search()
{
    btnSearch.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent ae) 
        {
            //String name = txtname.getText();

            String dataSourceName = "securitySystem";
            String dbUrl = "jdbc:odbc:" + dataSourceName;

            try{
                //Type of connection driver used    
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                //Connection variable or object param: dbPath, userName, password
                Connection con = DriverManager.getConnection(dbUrl, "", "");

                Statement statement = con.createStatement();

                ResultSet rs = statement.executeQuery("select * from accesshistory");

                String name = ""; 

                DefaultTableModel model;
                model = new DefaultTableModel(); 
                tableAccess = new  JTable(model);

                model.addColumn("Full Name");

                while(rs.next())  
                {
                    name = rs.getString("Name");      
                    model.addRow(new Object[]{name});
                }

                statement.close();
                con.close();
            }catch (Exception e) {
                try {
                    throw e;
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }                       
        }
    });

Upvotes: 0

Views: 104

Answers (2)

Yehia Awad
Yehia Awad

Reputation: 2978

  • First please for design purpose and robustness do never create a Database connection in an event handler would be better if added as a singleton and then called as static
  • Second take a look at this Post I guess what you are facing is an issue over JTableModel object declaration and allocation

Good luck

Upvotes: 0

tenorsax
tenorsax

Reputation: 21233

You seem to allocate new table component inside search() method. But this new table is not even added to a container. Do not reallocate the table component, instead use setModel() to refresh data. You can also update the existing model. See How to Use Tables for examples.

Also, for better user experience and performance do not execute long-running task such as database interaction on Event Dispatch Thread. Use an auxiliary thread, or a SwingWorker for that purpose. See Concurrency in Swing for details and examples.

Upvotes: 1

Related Questions