So I'm trying to use Key Bindings, and the action map's put() method takes an action and a string parameter.
/* all declartion is above
* the class extends JPanel so the keyword "this" can be used
* xlist is an ArrayList of Integers
* keyActionRight ka = new keyActionRight(x); is declared above, where x is a global int
* this is part of the keyBindingsTest class */
xlist.add(x);
im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right");
am = this.getActionMap();
am.put("right", ka);
System.out.println(ka.getNextX(xlist)); //Any way for this to be called just like if I printed in the actionPerformed of the action class?
This is the keyActionRight class. It is an action as you get an action when you extend AbstractAction:
public class keyActionRight extends
AbstractAction
{
private int x;
private ArrayList<Integer> xlist;
public keyActionRight(int x)
{
this.x = x;
xlist = new ArrayList<Integer>();
xlist.add(x);
}
public int getNextX(ArrayList<Integer> x)
{
x = xlist;
return x.get(0);
}
public void actionPerformed(ActionEvent e)
{
if(x != 440)
{
x++; //this incrementing works fine
xlist.add(0, x); //this updates xlist fine
}
}
}
The goal is essentially just to update the instance variable x in the keyBindingsTest class whenever I press or hold the right arrow key. The x in the Action class is updating just fine when I do this (I printed it out and it works). It's been pointed out why it's not updating - it is only being called once in the print statement. I want to know if there is a way to make this work with a separate class for the action or if I need to take a different approach.
I could try making the Action in the keyBindingsTest class, but that was giving me strange errors last time I tried that. Any help would be appreciated.
Thanks.
You have faulty assumptions:
xlist.add(x);
im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right");
am = this.getActionMap();
am.put("right", ka);
// **** the comment below is incorrect ****
//only prints out zero - should print out ascending values of x as I hold down the right arrow key
System.out.println(ka.getNextX(xlist));
The assumption you're making is that the println gets called when the Key Bindings action is called, but that is simply not so. The println is called once and only once when the key binding is created. The only code that gets called repeatedly is that which is within the Action's actionPerformed method, the code that is called in response to an event.
If you want code called multiple times and in response to an event, it must be placed within an event listener, not the listener's creation code.