java绘制小球自由下落

主类

import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class MyWindow extends JFrame{
    MyWindow(){
        this.setTitle("窗口");
        Container c = this.getContentPane();
        c.add(new TetrisPanel());
        this.setBounds(400,200,300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);//设置窗口大小不会变
        this.setVisible(true);
    }

    public static void main(String args[]){
        MyWindow DB = new MyWindow();
        DB.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }

}

线程类

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

public class TetrisPanel extends JPanel implements Runnable{//绘图线程类

    public int ypos = -80;
    private Image iBuffer;
    private Graphics gBuffer;

    public TetrisPanel(){
        //创建一个新的线程
        Thread t = new Thread(this);
        //启动线程
        t.start();
    }

    @Override
    public void run() {//重载类方法
        // TODO Auto-generated method stub
        while (true){
            try{
                Thread.sleep(30);
            }catch(InterruptedException e){}
            ypos += 5;//修改小球的纵坐标
            if (ypos > 300)
                ypos = -80;
            repaint();//床口重绘
        }
    }

    public void paint(Graphics g){//重载绘图方法
        super.paint(g);//将原来画布上的东西擦掉
        g.setColor(Color.RED);
        g.fillOval(90, ypos, 80, 80);
    }

}

你可能感兴趣的:(java)