Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JTable + KeyPress?

Status
Not open for further replies.

wangdong

Programmer
Oct 28, 2004
202
CN
How do I know the current row number when up/down key is pressed?

I try to add a KeyListener, but it doesen't do the job.

jTable.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent e) {
int row = jTable.getSelectedRow();
....
....
}
}

Chinese Java Faq Forum
 
I have a table with serveral text fields on a frame. When a user clicks on a table row, the fields values are displayed in the text fields. However, when the user uses up/down keys to switch between the rows, the text fields value are not updated. Therefore, I added a KeyListener to the table and try to get the selected row number. For some reason, this couldn't resolve my problem. Someone's got any idea?

Chinese Java Faq Forum
 
You should try ListSelectionListener. It never fails keeping track of all changes. This codeexample (not tested) should constantly keep currentRow up-to-date with current row in the table.
Code:
JTable myTable = new JTable();
ListSelectionModel lsm;
int currentRow = -1;
int prevRow = -1;

public myConstructor()
{
  lsm = myTable.getSelectionModel();
  lsm.addListSelectionListener(
    new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) return; // ignore
        ListSelectionModel lsm2 = (ListSelectionModel)e.getSource();
        if (!lsm2.isSelectionEmpty()) {
          prevRow = currentRow;
          currentRow = lsm2.getMinSelectionIndex();
        }     
      }
    }
  );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top