Hello,
I'm trying to get a JTable to behave when the arrow keys are pressed as if ctrl was being held down. In other words, when the user presses the up or down arrow, I want only the lead (the highlighted cell) to change, not the selection.
My thought was that I could use key bindings and Actions to set the arrow key actions equal to the arrow key plus ctrl Action. In a way, I'm trying to "trick" the JTable into thinking that ctrl is being held down when the arrow keys are pressed.
However, I'm pretty new to key bindings, and I'm getting a null pointer exception when I try to set the ctrl Action to occur when the arrow key (without ctrl) event is triggered. I've been through every tutorial I could find, and I'm still not sure what I'm doing wrong. Could anybody point me in the right direction?
Here's a piece of code using only the up arrow that demonstrates the problem:
import javax.swing.*;
import java.awt.event.*;
public class TestTableSelection{
JTable table;
public TestTableSelection(){
JFrame frame = new JFrame("Test Table Selection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//give the table random data
String [][] data = new String [10][5];
String [] names = new String [5];
for(int i = 0; i < 5; i++){
names[i] = "C: " + i;
for(int j = 0; j < 10; j++){
data[j] = "t: " + (int)(Math.random()*100);
}
}
table = new JTable(data, names);
//the arrows without ctrl is the key I want to reroute
Object key = table.getInputMap(JComponent.WHEN_FOCUSED).get(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
//the arrows with ctrl is the key of the action I want to reroute TO
Object ctrlKey = table.getInputMap(JComponent.WHEN_FOCUSED).get(KeyStroke.getKeyStroke(KeyEvent.VK_UP, java.awt.event.InputEvent.CTRL_DOWN_MASK));
//the action that occurrs when ctrl plus up is pressed
Action ctrlAction = table.getActionMap().get(ctrlKey);
//this should set the arrow without ctrl Action equal to the arrow with ctrl.. right?
table.getActionMap().put(key, ctrlAction);
frame.getContentPane().add(new JScrollPane(table));
frame.setSize(250, 250);
frame.setVisible(true);
}
public static void main(String[] args){
new TestTableSelection();
}
}Some print statements revealed that key, ctrlKey, and ctrlAction are all null, resulting in a NPE when I try to put key and ctrlAction into the table's ActionMap.
Does anybody see something I'm doing wrong? Is there a better way to accomplish my goal of changing the JTable behavior when an arrow is pressed?