代码如下:
package java2; import java.awt.Graphics; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class myframe07 extends JFrame{ //使用方向键操控圆,x,y是用来确定圆的坐标 int x=200; int y=100; int radius=15; myPane107 mp=new myPane107(); public myframe07() { // TODO 自动生成的构造函数存根 this.add(mp); mp.setFocusable(true); this.setTitle("test1_7"); this.setLocation(500,200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(600, 300); this.setVisible(true); event(); } private void event() { // TODO 自动生成的方法存根 mp.addKeyListener(new KeyAdapter() { //添加键盘事件监听器 new KeyAdapter(){}是键盘适配器要就是监听器 @Override public void keyPressed(KeyEvent e) { // TODO 自动生成的方法存根 if(e.getKeyCode()==KeyEvent.VK_UP) y-=10; //getKeyCode()是表示按键按下的序号,KeyEvent.VK_UP表示up(下)键的序号 if(e.getKeyCode()==KeyEvent.VK_DOWN) y+=10; if(e.getKeyCode()==KeyEvent.VK_LEFT) x-=10; if(e.getKeyCode()==KeyEvent.VK_RIGHT) x+=10; repaint(); } }); } class myPane107 extends JPanel{ @Override protected void paintComponent(Graphics g) { // TODO 自动生成的方法存根 super.paintComponent(g); g.drawOval(x-radius, y-radius, 2*radius, 2*radius); } } public static void main(String[] args) { // TODO 自动生成的方法存根 new myframe07(); } }运行图: 根据你的上下左右控制圆的移动