【问题标题】:Why does JTable only present 1st row of data?为什么 JTable 只显示第一行数据?
【发布时间】:2015-06-28 23:14:15
【问题描述】:

我开始学习如何使用数据库,并尝试将数据从我的 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 中。我已经在这个问题上停留了几个小时,但我不知道我做错了什么。提前致谢

【问题讨论】:

    标签: java database swing loops jtable


    【解决方案1】:

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

    i = i++;
    

    随便用

    i++;
    

    在进入循环之前还要初始化i

    【讨论】:

    • 这么简单的事情。非常感谢
    • 此外,您的数组索引出现错误 - 您不想为每行分配值 - data[i][0] = rs.getString("Author"); 等?
    【解决方案2】:

    您应该使用 for 循环或在循环之外声明 i。就目前而言,您将所有数据设置为第 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++;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多