JTable行标题的名称是数据库表列的名称

时间:2015-12-29 03:06:42

标签: java mysql swing jtable

当我制作表格时,(非硬编码的)Jtable的行标题设置为

| perf_title | perf_sdate | perf_edate | perf_stime | perf_etime |

但是从数据库中获取数据后,它变为

    try{
       String qwe = "SELECT perf_title, perf_sdate, perf_edate, perf_stime, perf_etime FROM performances";
       rs=st.executeQuery(qwe);
       jTable3.setModel(DbUtils.resultSetToTableModel(rs));
    }

    catch (SQLException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

这是数据库中的列名..

这是我的代码:

{{1}}

帮助?

enter image description here

1 个答案:

答案 0 :(得分:1)

基本代码如下:

//  Create an empty TableModel with just the column names

String[] columnNames = {"Performance Title", "Start Date", "...", "..."};
DefaultTableModel model = new DefaultTableModel(columnNames, 0)
{
    @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;
    }
};

//  Get each row of data from the ResultSet and add it to the TableModel

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 );