Search code examples
javasqljdbcderbyembedded-database

How can I populate my JTable with my embedded database?


I am having trouble showing my database filled JTable within my GUI application.

My code below runs through and creates a GUI with a panel, I then create my JTable and add it onto my application. I then run through a method that supposedly populates the table. After the populating has finished, nothing shows.

Dissecting my code, I'm led to believe somewhere is causing the data not to parse into my table, for some unknown reason, which is why I have come here.

At the click of a button, this code entails:

JTable tigerTable = new JTable();

JPanel centerPanel = new JPanel();

centerPanel.add(tigerTable, new GridBagConstraints());

FillTable(tigerTable, "SELECT * FROM TIGER_INFO");

The FillTable method as follows:

//Add buildTableModel method
public void FillTable(JTable table, String Query)
{
    try
    {

        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        Connection conn = DriverManager.getConnection("jdbc:derby:STOCK_CONTROL");
        Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = stat.executeQuery(Query);
        System.out.println("Connected");

        //Remove previously added rows
        while (table.getRowCount() > 0)
        {
            ((DefaultTableModel) table.getModel()).removeRow(0);
        }

        int columns = rs.getMetaData().getColumnCount();

        while (rs.next())
        {
            Object[] row = new Object[columns];

            for (int i = 1; i <= columns; i++)
            {
                row[i - 1] = rs.getObject(i);
            }
            ((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
        }

        rs.close();
        stat.close();
        conn.close();         
    }
    catch (InstantiationException |
            IllegalAccessException |
            ClassNotFoundException |
            SQLException e)
    {
        System.out.println(e);
        e.printStackTrace();
    }
}

Doing so creates the application, but does not show any table with data. My database contains 3 columns and 3 rows, but I do not see my data displayed inside a JTable.

My question is, how can I populate my JTable with my database and display it correctly on my GUI application?

If you need anything else, please let me know and I will provide as much as I can.

Thank you in advance.


Solution

  • I have found the solution - I've been trying to wrap my head around the problem for way too long, and I finally fixed it.

    Try setting the table model manually first.

    JTable tigerTable = new JTable();
    tigerTable.setModel(new DefaultTableModel(0, numberOfColumns));
    

    When you don't specify a model, the JTable creates an anonymous inner class and generally doesn't behave how you want it to.