我到底哪里错了,为什么不能动?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class move {
JFrame JF = new JFrame();
huabi hb = new huabi(0,0);
public void huamian(){
JF.setLocation(100, 100);
JF.setSize(500, 500);
JF.setVisible(true);
JF.add(hb);
JF.addKeyListener(new shijian());
}
@SuppressWarnings("serial")
class huabi extends JPanel{
int x;
int y;
public huabi(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
g.drawOval(10,10,50,50);
}
}
class shijian extends KeyAdapter {
public void keyPressed(KeyEvent e){
super.keyPressed(e);
if(e.getKeyCode()==KeyEvent.VK_UP)
{
System.out.println("上");
hb.x--;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
hb.y+=5;
}
hb.repaint();
}
}
public static void main(String args[]){
move m = new move();
m.huamian();
}
}
------解决方案--------------------JF也需要repaint。
class shijian extends KeyAdapter {
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if (e.getKeyCode() == KeyEvent.VK_UP) {
System.out.println("上");
hb.y-=5;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
System.out.println("下");
hb.y += 5;
}
hb.repaint();
JF.repaint();
}
}