所以我试图用箭头键和Key事件移动球,但是球没有移动。如果有人可以帮助我会很乐意欣赏它,并记住我是java的初学者。这是代码:
package prozor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyEvent;
@SuppressWarnings("serial")
public class prozor extends JPanel {
public int x = 0;
public int y = 0;
public boolean up,down,left,right;
public int vx,vy;
public void update(){
vx=0;
vy=0;
if(up)vy=-5;
if(down)vy=5;
if(right)vy=-5;
if(left)vy=5;
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN: down = true; break;
case KeyEvent.VK_UP: up = true; break;
case KeyEvent.VK_LEFT: left = true; break;
case KeyEvent.VK_RIGHT: right = true; break;
}
update();
}
public void moveBall() {
x +=vx;
y +=vy;
}
public void keyReleased(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN: down = false; break;
case KeyEvent.VK_UP: up = false; break;
case KeyEvent.VK_LEFT: left = false; break;
case KeyEvent.VK_RIGHT: right = false; break;
}
update();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 20, 20);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Sample Frame");
prozor game = new prozor();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}