Java
3
Вклад в тег
наверное добавить лисенер на саму форму окна приложения, тогда событие будет обрабатываться во всех случаях, когда окно приложения активно.
frame.addKeyListener(new MyKey());
Snake s = new Snake();
package application;
public class Application {
public static Snake s;
public static void main(String[] args) {
s = new Snake();
s.go();
}
}
package application;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import javax.swing.*;
import java.awt.event.KeyEvent;
public class Snake extends JComponent {
int x = 350;
int y = 350;
public MyPan drawPanel;
JFrame frame;
Timer timer = new Timer(100, new MyKey());
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new MyPan(this);
timer.start();
frame.getContentPane().add(drawPanel);
frame.setSize(700, 700);
frame.setVisible(true);
frame.setFocusable(true);
frame.setFocusTraversalKeysEnabled(false);
frame.addKeyListener(new MyKey());
frame.setFocusable(true);
}
public void moveRight() {
x += 10;
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
public void moveLeft() {
x -= 10;
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
public void moveDown() {
y += 10;
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
public void moveUp() {
y -= 10;
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyKey extends KeyAdapter implements ActionListener {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
moveRight();
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
moveUp();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
moveLeft();
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
moveDown();
}
}
@Override
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
}
}
package application;
import javax.swing.*;
import java.awt.*;
public class MyPan extends JPanel {
// Snake snake = new Snake();
private Snake s;
public MyPan(Snake ss) {
s = ss;
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 700, 700);
g.setColor(Color.GREEN);
g.fillRoundRect(s.x, s.y, 50, 50, 40, 40);
}
}