I am just getting into user input with java. I originally started out with KeyListener and then was told to use KeyBindings instead. I can't seem to get the Animation test to move when I press the right arrow key. Is this the proper way to implement keybindings or is there something that I need to add in one of these methods? Also is it possible to put all the input methods(the methods that handle the keybindings) into another class that can be accessed from? My main problem though is not being able to move the Animation test with the right arrow key.
public class EC{
Animation test = new Animation();
public static void main(String args[])
{
new EC();
}
public EC()
{
JFrame window=new JFrame("EC");
window.setPreferredSize(new Dimension(800,600));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(test);
window.pack();
window.setVisible(true);
addBindings();
}
public void addBindings()
{
Action move = new Move(1,0);
Action stop = new Stop();
InputMap inputMap = test.getInputMap();
ActionMap actionMap = test.getActionMap();
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_PRESS);
inputMap.put(key,"MOVERIGHT");
actionMap.put("MOVERIGHT",move);
key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_RELEASE);
inputMap.put(key, "STOP");
actionMap.put("STOP", stop);
}
class Move extends AbstractAction
{
private static final long serialVersionUID = 1L;
int dx,dy;
public Move(int dx,int dy)
{
this.dx=dx;
this.dy=dy;
test.startAnimation();
test.update();
}
@Override
public void actionPerformed(ActionEvent e) {
test.x+=dx;
test.y+=dy;
test.repaint();
}
}
class Stop extends AbstractAction
{
int dx,dy;
private static final long serialVersionUID = 1L;
public Stop()
{
test.stopAnimation();
test.update();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dx=0;
dy=0;
test.repaint();
}
}
}