亲宝软件园·资讯

展开

java反弹 java实现会反弹的小球示例

人气:0
想了解java实现会反弹的小球示例的相关内容吗,在本文为您仔细讲解java反弹的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();
        }
    }

}

加载全部内容

相关教程
猜你喜欢
用户评论