below's code is a code i wrote to get the value of 'monthly Depreciation' when i select the row on my jTable by either mouse-clicked or key-pressed. but it only selects the first value for 'monthly depreciation' when i click on the rows or key-press.the problem i know is coming from the where statement but can't seem to get around it.

 if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP)
        {
           try{
          int row =dep_report.getSelectedRow();
          String Table_click=(dep_report.getModel().getValueAt(row, 0).toString());
          String sql ="select Date_Acquired 'Date Acquired',Serial_Number 'Serial Number',"
                + " Description 'Description',Cost_Of_Acquisition 'Cost Of Acquisition',"
                + "Monthly_Depreciation 'Monthly Depreciation',Accumulated_Depreciation 'Accumulated                      Depreciation',Net_Book_Value 'Net Book Value'"
                + ",asset_update.Branch_Area 'Branch Area',Depts_name 'Department Name' ,User 'User',"
                + "Status 'Status' from items,asset_update where items.items_No = asset_update.items_No &&'"+Table_click+"'";
          pst = conn.prepareStatement(sql);
          rs = pst.executeQuery();


          if(rs.next()){
                String add1 = rs.getString("Monthly Depreciation");
                MonthlyDep.setText(add1);

            }

        }
        catch(Exception e)
        {
        JOptionPane.showMessageDialog(null, e);    
        }  

I would really appreciate the help thank you.

  • use ListSelectionListener, test if selectedRow > -1 (no row is selected), otherwise you will received a few nice exceptions from endless loop, and this code construction to freeze current JVM instance, can be closed from Taskbar only

  • change JTables SelectionMode to SINGLE_...., otherwise you have to loop inside arrays of selected rows

  • don't to use KeyListener for JTable, JTable isn't focusable by default, you have to create (forgot for Key_up, down, can by misspeled by another users decision, e.g. change selected row, edit cell, etc ....)

    1. use JPopupMenu

    2. create KeyBindigs for short_cut ALT/CTRL - S/R

    3. add JButton with Swing Action/ActionListener to JFrame,

    4. then there you can to run required code from selected row or arrays of selected rows against Database

  • JDBC is quite hard and long running task, you have to redirect all JDBC to Workers Thread, otherwise Swing GUI freeze, will be unresponsible for mouse & key events untill JDBC ended

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.