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();
            }
        }
    }
}

转载于:https://www.cnblogs.com/hjs775756009/p/6232975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值