2014-12-20 17 views
0

我通过这段代码填写在NetBeans一个JTable(tbl_student):JTable中选择一行为界,SQL服务器

String[][] result; 
    result = stu.Search(txt_search.getText()); 
    String hdr[] = {"code", "name", "family"}; 
    tbl_student = new JTable(result, hdr); 
    jScrollPane1.setViewportView(tbl_student); 
    tbl_student.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 

,搜索()函数是一个从表中选择在SQL Server中的所有查询数据库。 现在,我想在此表中查找选定的行。我该怎么做? 我的代码在这个jtable的鼠标点击事件不起作用! 我能做什么?

+0

你能提供更多的代码,什么是stu?它的类型是什么? – niceman

回答

1

如果在单击JTable中的某行时需要获取某些数据,请使用以下代码。

int row=tbl_student.getSelectedRow(); 
String Table_data=(tbl_student.getModel().getValueAt(row, 0).toString()); // In here 0 means the column number. 

//If you have a JTable with 5 columns; 0 is the 1st column and 4 is the last (5th) column. 

如果你想在一个数据库表中的数据向JTable,他们是一个叫rs2xml.jar与该库,你可以只需填写一个JTable与数据库中的数据的帮助库。

您可以从HERE下载该库。

下载库后使用下面的代码来填充您的JTable。

Connection conn=null; 
ResultSet rs=null; 
PreparedStatement pst=null; 

    try{ 
     String sql="SELECT * FROM table_name" 
     conn=java_connect.ConnecrDb();   //Database connecting class 
     pst=conn.prepareStatement(sql); 
     rs=pst.executeQuery(); 

     tbl_student.setModel(DbUtils.resultSetToTableModel(rs)); 
    } 
    catch(Exception e){ 
     JOptionPane.showMessageDialog(null, e); 

    } 

finally{ 
     try{ 
      rs.close(); 
      pst.close(); 
     } 
     catch(Exception e){ 
      JOptionPane.showMessageDialog(null, e);  
     } 
     }