如何更改JTable中列的名称

时间:2017-12-15 21:36:54

标签: java swing jtable

我需要在JTable中更改列的名称。现在,名称将自动从数据库中获取。我想将“country”和“sum”等列的名称更改为“国家名称”和“netamount的总和”。我使用Vector来创建我的JTable,所以更改名称是个问题。

我的代码:

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

1 个答案:

答案 0 :(得分:1)

如果要手动控制列名,可以执行以下操作:

String[] columnNames = {"Column1", "Column2", "Column3", "Column4"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0)

您将不再需要列名的元数据。

然后当您遍历ResultSet时,您只需:

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