Reputation: 487
I need to change the column's names in the JTable. Now names are automatically taken from the database. I want to change names of columns like "country" and "sum" for example to "Name of the country" and "Sum of the netamount". I use Vector to create my JTable, so it's a problem to change the names.
My code:
public class App extends JFrame{
public App() {
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
...
stmt = c.createStatement();
query = "select * from country";
rs = stmt.executeQuery(query);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement(md.getColumnName(i));
}
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement(rs.getObject(i) );
}
data.addElement(row);
}
rs.close();
stmt.close();
c.close();
}
catch(Exception e)
{
System.out.println(e);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
@Override
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;
}
};
JTable table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
App frame = new App();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
Upvotes: 0
Views: 2481
Reputation: 324207
If you want to manually control the column names you can do something like:
String[] columnNames = {"Column1", "Column2", "Column3", "Column4"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0)
You will no longer need the meta data for the column names.
Then when you loop through the ResultSet you just do:
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement(rs.getObject(i) );
}
model.addRow( row )
}
JTable table = new JTable( model );
Upvotes: 1