”仅有一个焦点组件能够接收KeyEvent。要使一个组件成为焦点组件,需要将属性isFocusable设置为true。“-----------------------------------------Ps:小细节,上下弄反了。y轴向下递增。-----------------------------------------------------修改方法之一见注释
package baidu;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MyGraphics3 extends JFrame{
public static void main(String[] args){
new MyGraphics3(100,100);
}
public MyGraphics3(int x,int y){
MGraphics3 mg = new MGraphics3(x, y);
mg.setFocusable(true); //设置为焦点组件!!!
add(mg);
//add(new MGraphics3(x,y));
setVisible(true);
setLocation(500,350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
}
}
class MGraphics3 extends JPanel{
private int x,y;
public MGraphics3(int x,int y){
this.x = x;
this.y = y;
addKeyListener(new Monitor3());
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.BLUE);
g.fillOval(x,y,10,10);
}
public void move(int a,int b){
x += a;
y += b;
repaint();
}
class Monitor3 extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP){
move(0,5);
}else if(e.getKeyCode() == KeyEvent.VK_DOWN){
move(0,-5);
}else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
move(5,0);
}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
move(-5,0);
}else{
System.out.println("ERROR!!!");
move(0,0);
}
}
}
}