package graphicalUserInterface;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
@SuppressWarnings("serial")
public class KeyBindingDemo2 extends JFrame {
public KeyBindingDemo2() {
this.setContentPane(new GamePanel());
}
class GamePanel extends JPanel {
private int x, y;
public GamePanel() {
Action downAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
y+=10;
}
};
Action upAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
y-=10;
}
};
InputMap inputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "downAction");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "upAction");
this.getActionMap().put("downAction", downAction);
this.getActionMap().put("upAction", upAction);
new Thread(new Runnable() {
public void run() {
while(true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
calculateNextPos();
}
}
}).start();
}
private void calculateNextPos(){
x+=5;
if (x>this.getWidth())
x=0;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x, y, 10, 10);
}
}
public static void main(String[] args) {
JFrame frame = new KeyBindingDemo2();
frame.setBounds(0, 0, 500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}