试图从“JTable”获取价值并将其设置为“Jtextfield”

时间:2013-08-15 11:28:20

标签: java sql swing jtable

我在这里看到了一些类似我的问题,但并不是所有问题都包括我的问题。我想从“JTable”中获取价值并将其设置为“Jtextfield”。我写了代码,但它不起作用。这是我的代码:

private void Table_EmployeeMouseClicked(java.awt.event.MouseEvent evt)
{                                            
        int row =Table_Employee.getSelectedRow();
        String Table_click=(Table_Employee.getModel().getValueAt(row, 0).toString());
        try{
        String sql ="select * from KYaziciProg where \"Müşteri Adı\"='"+Table_click+"' ";
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        if(rs.next()){

        String add1 =rs.getString("Yapılan İşlem");
        jTextField2.setText(add1);

        String add2 =rs.getString("Müşteri Adı");
        jTextField1.setText(add2);

        String add3 =rs.getString("Ürünün Cinsi");
        jTextField3.setText(add3);

        String add4 =rs.getString("Ürünün Miktarı");
        jTextField4.setText(add4);

        String add5 =rs.getString("Ürünün Fiyatı");
        jTextField5.setText(add5);

        String add6 =rs.getString("Ürünün Tutarı");
        jTextField6.setText(add6);

        String add7 =rs.getString("İşlem Tarihi");
        jTextField7.setText(add7);

        String add8 =rs.getString("Ödeme Vadesi");
        jTextField8.setText(add8);

        String add9 =rs.getString("Yapılan Ödeme");
        jTextField9.setText(add9);

        String add10 =rs.getString("Kalan Bakiye");
        jTextField10.setText(add10);
        }
       }catch(Exception e){
       JOptionPane.showMessageDialog(null, e);
       } 
    }                                           

1 个答案:

答案 0 :(得分:4)

  1. pst.close();rs.close();添加到finally块(try - catch - finally),否则这些对象会增加JVM内存

  2. 尽量避免将MouseListener用于此作业,这意味着private void Table_EmployeeMouseClicked(java.awt.event.MouseEvent evt)

  3. 每次单击鼠标来调用JDBC,但没有一些保证

    • 选择任何一行,因为默认情况下MouseEvents不仅可以选择JTable中的单元格,行或列

    • 只选择了一个单元格,行或列,否则您需要解决所选单元格,行,列的数组

    • 添加了ListSelectionListener

    • 将ListSelectionMode更改为SINGLE

  4. 修改

    • use action from JPopup for this job,从JPopup而不是从Mouse或ListSelectionListerner调用JDBC,然后你可以在JTable中使用所有鼠标键事件,而不管是否调用了JDBC

    • 然后我想念测试(否则是ArraysOf或NPE异常)伪代码

       int row =Table_Employee.getSelectedRow();
       if (row > -1) {  // no selection
         // now is possible to determine value
         // note see my next point about following code line
         // Table_Employee.getModel().getValueAt(row, 0).toString() 
       }
    

    String add1 = rs.getString("Yapılan İşlem");
    jTextField2.setText(add1);
    
    could be with success
    
    jTextField2.setText((rs.getString("Yapılan İşlem")).trim());