Shahul Basha
Shahul Basha

Reputation: 71

Populate JTable on press of TAB key

I have a JTable. User will enter an ID in a particular column and press TAB. I need to add event on that column to fetch value from DB and populate the rest of the columns of that row and create a new row for the next entry.

I am new to Swing and its difficult to find what is the best way to do it as i can see examples which were written in 2010 or so. Not sure if thats relevant still.

What I don't know:

  1. adding event handler to a particular column's cell in table.
  2. add next row after populating the data.

Upvotes: 0

Views: 384

Answers (2)

Prasad Karunagoda
Prasad Karunagoda

Reputation: 2148

You can use a TableModelListener for this. When user change ID column value, tableChanged() is invoked. Then the relevant data is fetched from the DB and set in the row. And a new row is added as well. Try below example.

(For demonstration purpose I have used a mock database in this example. It only gives rows for IDs "111" and "222".)

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;

public class TableDataChange
{
  public static void main(String[] args)
  {
    DefaultTableModel tableModel = new DefaultTableModel(
        new Object[][] {{"", "", ""}},
        new Object[] {"ID", "Column 2", "Column 3"});

    tableModel.addTableModelListener(new TableModelListener()
    {
      @Override
      public void tableChanged(TableModelEvent e)
      {
        String id = (String) tableModel.getValueAt(e.getFirstRow(), 0);
        if (id != null)
        {
          Vector row = Database.loadRowForId(id);
          tableModel.getDataVector().set(e.getFirstRow(), row);
          tableModel.addRow(new Vector());
        }
      }
    });

    JTable table = new JTable(tableModel);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(table));
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

// Mock database
class Database
{
  static Vector loadRowForId(String id)
  {
    Vector row = new Vector();
    if (id.equals("111"))
    {
      row.add("111");
      row.add("aaa");
      row.add("bbb");
    }
    else if (id.equals("222"))
    {
      row.add("222");
      row.add("ppp");
      row.add("qqq");
    }
    return row;
  }
}

Upvotes: 1

user10814567
user10814567

Reputation:

You can try something like this,

//Add Key Listener
table.addKeyListener(new KeyAdapter() {         
     public void keyPressed(KeyEvent event) {
         if (event.getKeyChar() == KeyEvent.VK_TAB) {
             int selectedColumn = table.getSelectedColumn();

             //Now you can search records related to ID and populate the table
         }
     }
});

Upvotes: 0

Related Questions