Recognize ENTER hit on JTable after cell edit is done
Hello,
I'm trying to find a way to detect a key press (specifically, Enter key) after editing a value on a JTable. That is, when I double click on a cell in my table, edit the value and press enter after the editing is done, I want to be able to detect pressing the enter. Adding a normal keyListener to the JTable object won't do it. So I'm trying to find a new way. Please help me out!
Here's my SSCCE:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
publicclass MyTableextends JTable{
JTable table;
public MyTable(Object[][] data, Object[] columnNames)
{
JFrame frame =new JFrame("My Table");
table =new JTable(data, columnNames);
JScrollPane scrollPane =new JScrollPane(table);
frame.getContentPane().add(scrollPane);
frame.setSize(100, 100);
frame.setVisible(true);
table.addKeyListener(new KeyAdapter()
{
publicvoid keyPressed(KeyEvent e)
{
if(e.getKeyChar()==KeyEvent.VK_ENTER)
{
System.out.println("Key Pressed");
}
}
});
}
publicstaticvoid main(String[] args){
// TODO Auto-generated method stub
Object [][]data ={{"item1"},{"item2"},{"item3"},{"item4"},{"item5"}};
String []columnNames ={"ITEMS"};
MyTable table =new MyTable(data, columnNames);
}
}
Message was edited by:
programmer_girl
# 1
First of all you don't use a KeyListener to check for KeyEvents on a compponent. You use "Key Bindings" and Actions:
http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
When you are "editing" a cell then focus is on the edtitor used by cell editor. For a cell containing Strings a JTextField is used. Since a JTextField supports an ActionListener all you need to do is get the JTextField and add an ActionListener to the text field. You can use the getDefaultEditor(...) method of JTable and cast the editor to a DefaultCellEditor. From there you can then get the editing component.
Of course the question is why are you specifically worried about the enter key? What if the user tabs to the next cell or uses the mouse to click on a different cell. There is more than one way to finish editing a cell.
# 5
> I figured out TableModelListener after I posted. Otherwise, I would have definitely mentioned it in my first post
I think you miss my point.
Your question should have been something like:
I want to know when the data of a cell has been edited. (the requirement)
I'm trying to handle the enter key on the cell editor (current approach).
Based on the requirement, we can then determine if you current approach is valid or suggest an alternative.
Instead I had to guess why you where trying to listen for the enter key and I start to ramble on about Key Bindings and Actions etc.
If I new the requirement from the start then I would have pointed you directly to the TableModel listener without confusing you with Key Bindings.