Adding keyboard functionality to JTable

Standard

I have spent a day chasing this down, so I thought I’d write it up for others searching for a solution.

For Hexxed I have the data displayed using a JTable class inside a ScrollPane.

I wanted to add additional keyboard driven events to this, but could find no way to get a KeyListener to work – it just seemed never to fire.

But the secret was to use key bindings to the JTable – like this:

	tableHex.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "Backwards")
	tableHex.getActionMap().put("Backwards", new HexxedBackAction(this))

Then with the Action class like this:

package hexedit

import java.awt.event.ActionEvent
import javax.swing.AbstractAction

class HexxedBackAction extends AbstractAction {

	def windowHexxed

	HexxedBackAction(def wHexxed)
	{
		windowHexxed = wHexxed
	}

	void actionPerformed(ActionEvent e)
	{
		windowHexxed.backward()
	}
}

I don’t fancy writing masses of Action classes for each key stroke, so I will investigate/remind myself the Groovy Meta Class interface for this – but at least the key functionality problem is cracked now.