0

I'm creating a billing software, I want to display the item names from the database that match the values typed in items column of my JTable. To accomplish this i have added a KeyListener. Everything works fine except that only for the first key, the keypressed event is triggered. If I press the enter key then type again, it gets triggered once again. I want the keyevent to be triggered for every key that is typed into the column continuously, can anyone help me out....?

I'll give the code snippet...I want the items from DB to be displayed in itable...

     public void keyPressed(KeyEvent e) {
        rows=table.getSelectedRow();
        cols=table.getSelectedColumn();
        if(cols==2){
           String code=(String)table.getValueAt(rows, cols);

           Statement stmt = null;
           ResultSet rs = null;

           for (int i =model1.getRowCount();i>0; i--) {
              model1.removeRow(i-1);
            }
            table.changeSelection(rows,cols, false, false);

           itable.setVisible(true);
           int i=0;
           String SQL = "SELECT * FROM items where name like\'"+code+"%\' or
                           code=\'"+code+"\' order by name";

           try{
               stmt =  (Statement) dbcon.con.createStatement();
               rs = stmt.executeQuery(SQL);
               while (rs.next()) {
                    model1.insertRow((i),new Object[]{""});
                    itable.setValueAt((Object)rs.getString("name"), i, 0);
                     i++;
                }

            }
            catch(Exception e1){
                  table.editCellAt(rows,cols,null);
                  return;

            }}
        }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Swami
  • 3
  • 1
  • 3

3 Answers3

1

That's probably because you're no longer in the JTable but in the CellEditor of the table.

Creates a JTextField with a key listener. Give it as editor for your table (via getColumn().setCellEditor()) And define your cell editor with "textCellEditor.setClickCountToStart(1);"

Anthony
  • 1,245
  • 1
  • 16
  • 15
1
  • don't use KeyListener for Swing JComponents, this Listener isn't designated for JTextComponents nor for Compound JComponents as JTable, JSpinner or JComboBox are

  • don't runs ResultSet against Database on every events, nor to opening JDBC Connection, because these two action can take long time and GUI in this form waiting until ResultSet ended

  • Connection, Resultset and Statement must be close(), and into finally block (try - catch - finally) otherwise stays in the memory, Database can have got reduced number of connections too, you can to get OutOfMemory or Database can refuse opening a new connection because you overloading maximum numbers of opened concurent connections

  • your code talking about loading reduced number of records to the AutoCompleted JComboBox or JTextField, only once time on aplications Start_Up,

  • then you can to ask a new question How to .....

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

The problem is that as soon as you type a key with the table selected, the table will start editing that selected item (and all the following key events will be directed to that 'TableCellEditor').

Assuming you don't want any of your data to be editable this way, an easy solution is overriding the 'DefaultTableModel' so none of the data is editable.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class TestProject extends JPanel{

    public TestProject(){
        super();

        //Use default table model - only make it so no cells are editable
        final DefaultTableModel model = new DefaultTableModel(0, 5){
            @Override
            public boolean isCellEditable(int row, int column){
                return false; // makes no table cells editable
            }
        };

        //Create table off of Table Row
        final JTable table = new JTable(model);
        for(int i = 0; i < 20; i++){
            model.addRow(new String[]{i+".1", i+".2",i+".3",i+".4",i+".5",});
        }

        add(table, BorderLayout.CENTER);

        //Add Key Listener
        table.addKeyListener(new KeyAdapter() {         
             public void keyPressed(KeyEvent e) {
                 System.out.println("pressed");
                 char key = e.getKeyChar();
                 int selectedColumn = table.getSelectedColumn();

                 //Update info in table
                 for(int i = 0; i < model.getRowCount(); i++){
                     String value = (String)model.getValueAt(i, selectedColumn);
                     model.setValueAt(value + key, i, selectedColumn);
                 }
             }
        });
    }

    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                frame.setContentPane(new TestProject());    
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
Nick Rippe
  • 6,465
  • 14
  • 30