我已经看了这个教程并按照我所学到的有一个矩形,按下箭头键时应向上,向下,向右移动。然而,我得到的唯一动作是左右按下的对角线移动,而向上和向下箭头键显然不做任何工作。
有人可以分析我的代码并告诉我为什么我会得到对角线移动而不是向左,向右,向下移动? 谢谢你的期待。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Paint extends JPanel implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
int x=0, sx=0, y=0, sy=0;
Timer t= new Timer(5,this);
public Paint(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 50, 50);
}
@Override
public void actionPerformed(ActionEvent e) {
x=x+sx;
y=y+sx;
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
int c= e.getKeyCode();
if(c== KeyEvent.VK_LEFT){
sx=-1;
sy=0;
}
if(c== KeyEvent.VK_RIGHT){
sx=1;
sy=0;
}
if(c== KeyEvent.VK_UP){
sx=0;
sy=-1;
}
if (c== KeyEvent.VK_DOWN){
sx=0;
sy=1;
}
}
public static void main(String [] args){
Paint p= new Paint();
JFrame j= new JFrame();
j.setTitle("Practice");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(500,500);
j.setLocationRelativeTo(null);
j.setVisible(true);
j.add(p);
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:7)
看到这段代码:
x=x+sx;
y=y+sx; <--- should be sy