java_多线程_移动的小球与按钮

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestMoveBall extends JFrame {
    private JButton jb;
    private MyPanel mp;
    private Thread t;
    public TestMoveBall(){
        this.setSize(1024, 720);
        this.setLocation(400,400);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        
        jb=new JButton("移动小球");
        mp=new MyPanel(50, 50);
        
        jb.addActionListener(new BtnClickEvent());
        this.add(jb,BorderLayout.NORTH);
        
        this.add(mp);
        t=new Thread(mp);
        this.setVisible(true);
    }
    class BtnClickEvent implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==jb){
                t.start();
                }
        }
    }
    public static void main(String[] args) {
        new TestMoveBall();
    }
    
class MyPanel extends JPanel implements Runnable{
        int x,y;
        public MyPanel(int x,int y){
            this.x=x;
            this.y=y;
        }
        public void paint(Graphics g){
            super.paint(g);
            //设置颜色
            g.setColor(Color.RED);
            //画出一个椭圆
            g.fillOval(x, y, 50, 50);
        }
        public void run() {
            try {
                for(int i=0;i<20;i++){
                    mp.x+=3;
                    mp.repaint();//另外一个程序执行
                }
                Thread.sleep(25);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
posted on 2016-12-29 14:48  多情剑客无情剑26  阅读(260)  评论(0编辑  收藏  举报