jtable只返回数据库中的一行

时间:2015-06-14 12:26:51

标签: java mysql swing

我希望表从数据库返回数据而不指定行数,我在默认的tablemodel中使用了自动增量,但它没有显示所有行,我必须在actionlistener之外定义表以便添加它到JPanel,所以问题是我的表只返回数据库的一行

int row = 1;
     Object [] colnames = {"year","term","balance"};
     JTable table4 = new JTable(new DefaultTableModel(colnames,++row));
     JScrollPane pane  = new JScrollPane(table4);





 saachs.addActionListener(new ActionListener(){

       public void actionPerformed(ActionEvent e) {
             String adm = adms.getText();
             int row = 0;

            Connection con = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                try {
                    throw new Exception ("driver not found");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            String url = "jdbc:mysql://localhost/test";
              try {
                con = DriverManager.getConnection(url,"abda","abda");
            } catch (SQLException e1) {
                e1.printStackTrace();
            }if(con!=null){
                Statement st = null;
                ResultSet rs = null;
                String query = "select a.year,a.term,a.payable - b.total_paid balance from seet a join ( select adm, extract(year from date) tyear,class, term, sum(paid) total_paid from fees group by adm,class,term) b on a.class = b.class and b.adm = '"+adms.getText()+"' and a.term = b.term and a.year = b.tyear";

                try {
                    st = con.createStatement();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    rs = st.executeQuery(query);
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                try {
                    while(rs.next()){
                        table4.setValueAt(rs.getString(1),row,0);
                        table4.setValueAt(rs.getString(2),row,1);
                        table4.setValueAt(rs.getString(3),row,2);

                        row++;
                    }
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }


        }

    });

1 个答案:

答案 0 :(得分:1)

不要使用setValueAt(...)方法直接设置JTable的值,而是在actionPerformed(...)方法中创建DefaultTableModel对象,并在while (rs.next())方法内创建新的{{1}您使用ResultSet的当前行中的数据填充,并在while循环的末尾,通过调用其Vector<String>方法将此Vector传递到模型中。然后通过调用表的addRow(Vector v)方法将此模型传递给JTable。

类似的东西:

setModel(TableModel model)

警告:代码未经过测试