我试图使用箭头键移动一个盒子,但我似乎无法让它响应我的键:/。我看了几个教程来做到这一点,我不明白为什么我的代码不起作用。
基本上我试图让这个盒子像经典乒乓球游戏一样,除了它在底部,它只在X轴上移动。
如果有人能发现为什么我的盒子没有回应我的关键事件,我真的很感激=) 我有2个类,主要和类包含"播放器",这是盒子。
主:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main extends JPanel implements KeyListener {
Player player;
Main() {
player = new Player();
this.addKeyListener(this);
this.requestFocusInWindow();
}
public void update() {
player.move();
this.repaint(); //runs the paint method on the object
}
@Override
public void paint(Graphics g) {
super.paint(g);
player.paint(g);
}
public static void main(String[] args) {
int width = 800;
int height = 600;
JFrame frame = new JFrame("Pinball"); //create a new window and set title on window
frame.setSize(width, height); //set size of window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the window to close when the cross in the corner is pressed
Main m = new Main(width,height-22); //-22 to account for menubar height //create a new object and runs constructor for initial setup of the program
frame.add(m); //add the content of the object to the window
frame.setVisible(true); //make the window visible
while (true) { //keep running a loop
//each time the loop is run do
m.update(); //run the update method on the object
try {
Thread.sleep(10); //stops this part of the program for 10 milliseconds to avoid the loop locking everything. Now the screen has time to update content etc.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code==KeyEvent.VK_RIGHT){
player.setRight(true);
}
else if(code==KeyEvent.VK_LEFT){
player.setLeft(true);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
播放器:
package com.company;
import java.awt.*;
/**
* Created by John on 13/03/2015.
*/
public class Player {
private Boolean left = false, right = false;
int xPos=200;
Player() {
}
public void move(){
if(left){
xPos-=2;
}
else if(right){
xPos+=2;
}
}
public void paint(Graphics g){
g.fillRect(xPos,500,20,20);
}
public void setLeft(Boolean b){
left=b;
}
public void setRight(Boolean b){
right=b;
}
}