Java - ResultSet change Db column names to show in JTable

拈花ヽ惹草 提交于 2019-12-11 14:49:52

问题


I am using rs2xml.jar for populating data into table. here is my code of showing table columns and data

ResultSet rs = stmt.executeQuery("select * from employees");

table_employees.setModel(DBUtiles.resultSetToTableModel(rs));

This code successfully works But I want to rename the columns. I don't want to show the DB Columns in my table.


回答1:


You need to update the TableColumn from the TableColumnModel:

TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(0).setHeaderValue("whatever you want");

Or you can override the getColumnName(...) method when you create your JTable:

JTable table = new JTable( DBUtilities.resultSetToTableModel(rs)
{
    private String[] columnNames = 
    {
        "Column 1",
        "Column 2",
        "Column ..."
    };

    @Override
    public String getColumnName(int col) 
    {
        return columnNames[col];
    }
};



回答2:


You can consider using the code below if you wish to use DB values with java column names and you can set the column names in java using the TableModel property of the jTable.

DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();
tmodel.addRow(new Object[] {....});
jTable1.setModel(tmodel);

Hope this helps.




回答3:


You can get column name as per your choice from Sql query like

SELECT column name as 'Student Id', Column Name as 'Student name' FROM student;

Query give you result with column name as per you decide.



来源:https://stackoverflow.com/questions/24218546/java-resultset-change-db-column-names-to-show-in-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!