import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class liatener extends JFrame {
int x=200;
shu si=new shu();
liatener(){
super("监听");
setBounds(100,100,600,600);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(si);

JButton jbutton=new JButton();
jbutton.setBounds(10,530,70,30);
jbutton.setText("开始");
jbutton.addActionListener(new ActionListener()
{                                //监听的添加
public void actionPerformed(ActionEvent e)
{
Thread th2 = new Thread(si);
th2.start();
System.out.println("正在画图"); } });
add(jbutton);
}


public static void main(String[] args){
new liatener();
}
}import java.awt.*;
import java.awt.event.*;public class shu extends Canvas implements KeyListener,Runnable
{                                                      //加入画布框
int x=105;
int d=21,b=42,c=63;
int y=0;
int q=21,w=42,e=63;
int a=1000;
public shu()
{
setBounds(0, 0, 293, 419);
setBackground(Color.RED);
    addKeyListener(this);
}
public void paint(Graphics graphics)  //重写paint()方法        //Graphics graphics = new Graphics();
{   
graphics.setColor(Color.blue);
graphics.fillRect(x, y, 20, 20);
graphics.fillRect(x+ d, y, 20, 20);
graphics.fillRect(x+ c, y, 20, 20);
graphics.fillRect(x+ b, y, 20, 20);

}
public void update(Graphics graphics)
{

Image off = this.createImage(this.getWidth(),this.getHeight());
Graphics offbuf = off.getGraphics();
paint(offbuf);
graphics.drawImage(off, 0, 0, this.getWidth(), this.getHeight(), null);
//System.out.println("正在画图");
} public void run()
{
while (true)
{
if (y== 399)
{
Thread th=new Thread(this);
th=null;
}
else{
try
{
Thread.sleep(a);
System.out.println("正在画图");
}
catch (Exception e)
{
e.printStackTrace();

}
q=0;w=0;e=0;
requestFocus();
y= y+21;
repaint();
}
}
}
public void keyReleased(KeyEvent e){ }
public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
b=0;c=0;d=0;
break;
case KeyEvent.VK_DOWN:
y=y+21;
repaint();
System.out.println("按下down键");
break;
case KeyEvent.VK_LEFT:
if(x==0){
x=0;
repaint();
System.out.println("你好!");
}else{
x=x-21;
repaint();
}System.out.println("按下left键");
break;
case KeyEvent.VK_RIGHT:
if(x==210){
x=210;
repaint();
}else{
x=x+21;
}System.out.println("按下right键");
break;
}
}
}