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