I am filling a JTable with data from a database. I am have subclassed AbstractTableModel and passed the reference to the JTable. However, how do I manage to extract the column names in the database and set them as "headers" in the JTable?
Thanks in advance.
I already have this, in the console the header names display but I do not have a column in the GUI. I have attached the JTable to a tab in a tabbed pane.
@Override开发者_StackOverflow
public String getColumnName(int column) {
try {
System.out.println(dbhandler.getMetaData().getColumnName(column + 1));
return dbhandler.getMetaData().getColumnName(column + 1);
} catch (SQLException e) {
e.printStackTrace();
return "";
}
}
However, how do I manage to extract the column names in the database and set them as "headers" in the JTable?
Your table model needs to implement the getColumnName() method. Then you need to create your table model with data first. Then you create your JTable using the table model and the table will build the columns for you.
See Table from Database for code that provides a reusable table model as well as a method to populate the table for you automatically.
I do not have any columns at all, it is all rows...
You need to add the table to a JScrollPane (not a JPanel) and the headers will appear as the column header view of the scroll pane:
JScrollPane scrollPane = new JScrollPane( table );
You can do it by overriding getColumnName(int i) method of AbstractTableModel, and put your "header" Strings in this method.
How do you get your data? With a "SELECT * FROM foo"?
Interface: java.sql.DatabaseMetaData
getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) Retrieves a description of table columns available in the specified catalog.
Did you override getColumnCount also?
private void getColumnsFromDB (Connection connection, String tname) throws SQLException
{
String query = "SELECT * FROM " + tname;
Statement stmt = connection.createStatement ();
ResultSet res = stmt.executeQuery (query);
ResultSetMetaData rsmd = res.getMetaData ();
int numberOfColumns = rsmd.getColumnCount ();
boolean searchable = rsmd.isSearchable (1);
if (searchable)
{
for (int j = 1; j <= numberOfColumns; ++j)
{
Column col = new Column (tname, rsmd, j);
// do something with Column (col);
}
}
}
Class Column, Ctor:
public Column (String t, ResultSetMetaData rsmd, int j) throws SQLException
{
table = t;
name = rsmd.getColumnName (j);
schema = rsmd.getSchemaName (j);
precision = -1;
try
{
precision = rsmd.getPrecision (j);
}
catch (NumberFormatException nfe)
{
System.err.println ("nfe[gtd]: " + nfe + " " + t.getName () + "." + name);
}
scale = rsmd.getScale (j);
catName = rsmd.getCatalogName (j);
coltype = rsmd.getColumnType (j);
coltypeName = rsmd.getColumnTypeName (j);
int nulling = rsmd.isNullable (j);
nullable = NULLTYP [nulling];
}
I hope it works, because this code is part of a much larger Codebase, and it's long ago I worked with it.
精彩评论