2014-12-20 44 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);  
     } 
     }