AIR
AIR

Reputation: 73

Column header do not show up even after wrapping the table with JScrollPane

This is a followup question to Display database table with swing

I wrapped my table to a JScrollPane but the columns' headers are still not showing up!

Can anyone tell me what is wrong?

try {
    con = (Connection) DriverManager.getConnection(DATABASE_URL , USERNAME, PASSWORD);
    stmt = (Statement) con.createStatement();
    ResultSet rs = stmt.executeQuery(QUERY_FIND_ITEMS);

        {
    ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
    int columns = md.getColumnCount();

    //  Get column names
    for (int i = 1; i <= columns; i++)
    {
        columnNames.add( md.getColumnName(i) );
    }

    //  Get row data
    while (rs.next())
    {
        ArrayList row = new ArrayList(columns);

        for (int i = 1; i <= columns; i++)
        {
            row.add( rs.getObject(i) );
        }

        data.add( row );
    }
}
}   
catch (SQLException e)
{
    System.out.println( e.getMessage() );
}

Vector<String> columnNamesVector = new Vector();
Vector dataVector = new Vector();

for (int i = 0; i < data.size(); i++)
{
    ArrayList subArray = (ArrayList)data.get(i);
    Vector subVector = new Vector();

    for (int j = 0; j < subArray.size(); j++)
    {
        subVector.add(subArray.get(j));
    }
    dataVector.add(subVector);
}

for (int i = 0; i < columnNames.size(); i++ ) {
    columnNamesVector.add(columnNames.get(i));
}
//  Create table with database data    
JTable table = new JTable(dataVector, columnNamesVector)
{
    public Class getColumnClass(int column)
    {

        for (int row = 0; row < getRowCount(); row++)
        {
            Object o = getValueAt(row, column);

            if (o != null)
            {
                return o.getClass();
            }
        }


        return Object.class;
    }
};


          JScrollPane scrollPane =new JScrollPane(table);
            getContentPane().add( scrollPane, BorderLayout.WEST );

            JPanel buttonPanel = new JPanel();
            getContentPane().add( buttonPanel, BorderLayout.SOUTH );

            table.setForeground(Color.BLUE);

Upvotes: 1

Views: 38

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

catch (SQLException e)
{
    System.out.println( e.getMessage() );
}

The code after the end of the catch block will not work correctly if the DB query fails. Best to include that code within the try block.

And a tip: change

System.out.println( e.getMessage() ); 

to

e.printStackTrace(); 

Both shorter & more informative.

Upvotes: 2

Related Questions