大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
”仅有一个焦点组件能够丛旅漏接收KeyEvent。要使一个组件成为焦点组件,需要将属性isFocusable设置为true。“
创新互联建站自2013年起,是专业互联网技术服务公司,拥有项目成都网站设计、网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元泽州做网站,已为上家服务,为泽州各地企业和个人服务,联系电话:18982081108
-----------------------------------------
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);
}
}
}
}