Search code examples
javaswingevent-handlingjtablecell

How to get the currently selected cell's indices in JTable immediately after it is highlighted?


I'm building a spread sheet application. But this is not a question like using table.getSelectedColumn() and table.getSelectedRow() to find the selected cell in a JTable.

In Microsoft Excel, when we navigate through cells using arrow keys, the content in the cells are displayed in the Formula Bar immediately after highlighting the cell. Here, the most important thing is, when a cell is highlighted by the selection as above, the value inside the cell is displayed at the sametime. So my question is, how can we do the same in JTable?

I have tried to do something similar using keyEvent listener, but the problem with that is, when a key event is generated, the next cell is being highlighted but the indices of the previous(which was previously highlighted) is being returned in the getSelectedRow() and getSelectedColumn() methods. Also i tried the ListSelectionListener. but the same fault exists.

If there's any way to get the selected cell's indices immediately after the new cell is highlighted when navigated using arrow keys, that will work. Also an event should be generated since I want to update the formula bar as in Excel. Can someone help me with this?

Thanks in advance!


Solution

  • You can use this simple trick! Only have to make two excess jTextfields. (can set to be invisible at the run time)

    Try to get an idea from below code segment.

    private int r;
    private int c;
    private String buffer;
    
    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {                                     
        jTextField2.requestFocus();
        buffer = jTextField1.getText();
        jTable1.getModel().setValueAt(jTextField1.getText(), r, c); 
    }                                    
    
    private void jTable1KeyTyped(java.awt.event.KeyEvent evt) {                                 
        r = jTable1.getSelectedRow();
        c = jTable1.getSelectedColumn();
        jTable1.putClientProperty("terminateEditOnFocusLost", true);
    
        jTextField1.requestFocus();
    }                                
    
    private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {                                        
        buffer = (String)jTable1.getModel().getValueAt(r, c);
        jTextField1.setText(buffer);
        jLabel1.setText(buffer);   
    }                                       
    
    private void jTextField2FocusGained(java.awt.event.FocusEvent evt) {                                        
        buffer = jTextField1.getText();
        jTable1.getModel().setValueAt(buffer, r, c);
        jTextField1.requestFocus();
    }