为什么JTable只提供第一行数据?

时间:2015-06-28 23:14:15

标签: java database swing loops jtable

我开始学习如何使用数据库,并尝试将数据从我的h2数据库导出到JTable中。该表提供了正确的行数,但是,只有第一行填充了数据。其余的是空格。我在JTable下面发布了一些代码。如果有人需要查看更多代码,我会发布它。

public class Table extends JTable{

    public static int rows;
    public static String[][] data;
    public static String[] columns = {"Author", "Customer", "Date"};

    public static void populateTable() throws ClassNotFoundException, SQLException{

//Server is name of the database class
        Server server = new Server();

        Statement stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);        
        ResultSet rs = stat.executeQuery("SELECT * FROM data");
        rs.last();
        rows = rs.getRow();
        rs.beforeFirst();

        data = new String[3][rows];

        while(rs.next()){
           int i = 0;
           data[0][i] = rs.getString("Author");
           data[1][i] = rs.getString("Customer");
           data[2][i] = rs.getString("Date");
           System.out.println(rs.getString("Author"));
           i = i++;
        }
        rs.close();
    }
}

class MyTableModel extends DefaultTableModel{

        String[] columnNames = {"Author", "Customer", "Date"};

        MyTableModel() throws ClassNotFoundException, SQLException{
            addColumn(columnNames[0]);
            addColumn(columnNames[1]);
            addColumn(columnNames[2]);
        }

        @Override
        public int getRowCount() {
            return rows;
        }

        @Override
        public int getColumnCount() {
            return 3;
        }

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

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
                return data[columnIndex][rowIndex];

    }

我也能够在控制台上打印所有数据,但它只是不会出现在JTable中。几个小时我一直坚持这个问题,但我不知道自己做错了什么。提前致谢

2 个答案:

答案 0 :(得分:3)

此语句是无操作,因为i在递增之前已分配

i = i++;

只需使用

i++;

在进入循环之前初始化i

答案 1 :(得分:2)

您应该使用for循环或在循环之外声明我。就目前而言,您将所有数据设置为第0行(int i = 0);

while(rs.next()){
           int i = 0; // this will run for every row
           data[0][i] = rs.getString("Author");
           data[1][i] = rs.getString("Customer");
           data[2][i] = rs.getString("Date");
           System.out.println(rs.getString("Author"));
           i = i++;
        }