작은 게임 애플릿을 만들고 있는데, 플레이어가 컨트롤을 가지고 돌아 다니는 곳으로가 보았습니다.Java keyPressed() 메소드는 플레이어가 탭을 누른 후에 만 작동합니다.
주요 :
public class Main extends JApplet implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
private static DoubleBufferedCanvas canvas = new DoubleBufferedCanvas();
public static int width = 900;
public static int height = 600;
public static int fps = 60;
public static Ailoid ailoid = new Ailoid();
public static Player player = new Player();
// Initialize
public void init() {
setSize(width, height);
setBackground(Color.white);
add(canvas);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
ailoid.setLocation(new Location(100, 100));
AlienManager.registerAlien(ailoid);
player.setLocation(new Location(400, 400));
}
// Paint graphics
public void paint(Graphics g) {
super.paint(g);
}
// Thread start
@Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
// Thread stop
@Override
public void destroy() {
}
// Thread run
@Override
public void run() {
Thread thread = new Thread(this);
while (thread != null) {
Updater.run();
canvas.repaint();
try {
// 1000 divided by fps to get frames per second
Thread.sleep(1000/fps);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent evt) {
KeyPress.run(evt);
System.out.println("DEBUG");
}
@Override
public void keyReleased(KeyEvent evt) {
}
@Override
public void keyTyped(KeyEvent evt) {
}
}
무슨 일 그것은 단지 내가 탭을 누른 후 "디버그"라고 시작하는 것입니다. 플레이어가 탭을 누르지 않아도 어떻게 작동합니까?
'KeyPress.run (evt);는 무엇입니까? – BitNinja
1) 애플릿이 표시하는 JPanel의'paintComponent (Graphics g)'메소드를 그린다. 이것은 더블 버퍼링과 깜박 거림을 줄 것이다. 2) KeyListeners는 사용하지 말고, Swing 어플리케이션이므로 Key Binding을 사용하십시오. Key Binding은 포커스 할 때보다 유연합니다. –