欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现会反弹的小球示例

程序员文章站 2024-02-26 18:23:40
java实现简单的球的弹射,碰到墙壁就反弹一下,代码如下  复制代码 代码如下:package tsct; import java.awt.color;imp...
java实现简单的球的弹射,碰到墙壁就反弹一下,代码如下 

java实现会反弹的小球示例

复制代码 代码如下:

package tsct;

import java.awt.color;
import java.awt.graphics;
import java.awt.image;
import java.awt.event.windowstatelistener;
import java.io.file;
import java.io.ioexception;

import javax.imageio.imageio;
import javax.swing.jframe;

public class main extends jframe implements runnable
{
    int x=40;
    int y=30;
    int width=50;
    int height=50;
    boolean xadd=true;
    boolean yadd=true;
    public void paint(graphics g)
    {
        super.paint(g);
        //g.fillrect(x, y, width, height);
        g.setcolor(color.red);
        g.filloval(x, y, width, height);
    }
    int i=1;
    @override
    public void run()
    {
        // todo auto-generated method stub
        while(true)
        {
            if(yadd)
                y+=15;
            else
                y-=15;
            if(y>=this.getheight()-height||y<=25)
                yadd=!yadd;
            if(xadd)
                x+=30;
            else
                x-=30;
            if(x>=this.getwidth()-width||x<=5)
                xadd=!xadd;
            repaint();
            try
            {
                thread.sleep(40);
                i++;
            }
            catch (interruptedexception e)
            {
                e.printstacktrace();
            }
        }
    }
    public static void main(string[] args)
    {
//        main main=new main();
//       
//        main.setvisible(true);
//        main.run();
        main main=new main();
        main.setvisible(true);
        main.setbounds(50, 50, 800, 600);
        thread thread=new thread(main);
        thread.start();
        try
        {
            image image=imageio.read(new file(main.class.getresource("").tostring()));
        }
        catch (ioexception e)
        {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

}