By default, pressing the TAB key in a JTextArea will insert a tab character instead of transferring focus to the next focusable component. But if your JTextArea is a cell editor within a JTable, and you want the TAB key to transfer to the next cell on an on, what I did was add a KeyListener to the JTextArea and capture the TAB key event when pressed, then calling the JTable changeSelection() method to transfer focus to the next cell.

If the focus was on the last column of a row, it will check if there is another row next to it. If there is, focus will be transferred to the next row on the first column and so on and so forth. Here is the source code for my TextAreaCellEditor class.

If you want the TextAreaCellEditor class to implement trapping the TAB key event, just supply a boolean parameter true to the constructor.

Focus traversal from cell to cell in a JTable seems to be a very interesting topic. I scoured the internet looking for a solution and it was not easy. People suggested about focus traversal among others which did not work. One person in a forum mentioned overriding the changeSelection method of the JTable that made it work.

That’s it. Whenever you press the TAB key if the JTable has focus, the focus will transfer to the next cell. If your cell has an editor associated to it and if the editor returned is a container like a JPanel, you can modify code in your cell editor class and add a FocusListener to the panel object while adding code in the focusGained() method and call requestFocusInWindow() to the Swing component that you want to receive focus.

If you use a JComboBox as a cell editor in a JTable and you get this error message “component must be showing on the screen to determine its location”, chances are your cell editor is inherited from DefaultCellEditor. Thomas Bang saved us all the trouble in trying to figure out how to make a workaround for this problem by creating a ComboBoxCellEditor class inheriting from AbstractCellEditor.

Pretty cool. This class actually did the trick.

Related Posts Plugin for WordPress, Blogger...