Reputation: 63
I have a three-column JTable: an uneditable JTextField, an editable JTextArea, and an editable JTextField.
My problem is twofold. I'd like the last two columns to be background-highlighted and ready to edit, with a visible cursor, when I tab into them. They also use a specific font; hence the custom renderers and editors.
I'm successful if I click twice in one of the cells, but not if I use the keyboard to get there. I can tab from cell to cell (thanks to a setTraversalKeys call for the JTextArea) and start typing, but where the focus is isn't apparent.
I have an focus event listener which sets the background color on whichever component triggers it. It's used on the JTextField and JTextArea used for cell editing, and on the cell renderers for good measure. But only a mouse click will trigger them.
How can I ensure the focus event is triggered on the cell I'm tabbing into?
Thanks.
Upvotes: 0
Views: 537
Reputation: 63
Thank you, all. This is what I ended up with:
ListSelectionListener listener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
// Only columns beyond the first are edited...
if (row != -1 && col > 0) {
table.editCellAt(row, col);
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_F2);
robot.keyRelease(KeyEvent.VK_F2);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
};
The cell editors created in response to the editCell() call set the background color on the JTextArea and JTextField they use. The Robot's purpose is to simulate depression of F2, and thus reveal the cursor (wrong term, I know, but the correct one escapes me).
The Robot works when tabbing forward, but not backward, although the shading occurs. I don't know whether this code snippet is executed in that case, although the cell editor gets created somehow. Since this program is for only my own use, I'll try solving that little problem some other day.
Upvotes: 0
Reputation: 10143
You should listen to selection change and start edit where you need it:
final JTable table = new JTable (
new String[][]{ { "col1", "col2", "col3" }, { "col1", "col2", "col3" } },
new String[]{ "1", "2", "3" } );
ListSelectionListener listener = new ListSelectionListener ()
{
public void valueChanged ( ListSelectionEvent e )
{
if ( table.getSelectedRow () != -1 && table.getSelectedColumn () != -1 )
{
table.editCellAt ( table.getSelectedRow (), table.getSelectedColumn () );
}
}
};
table.getColumnModel ().getSelectionModel ().addListSelectionListener ( listener );
table.getSelectionModel ().addListSelectionListener ( listener );
Thats just an example how you could do that.
Upvotes: 1