一个用JAVA编写的多线程小球运动的东西
萌到你眼炸
891次浏览
2020年08月02日 09:25
最佳经验
本文由作者推荐
硫酸根-倾盆
* Created on 2005-3-20
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/**
* @author pingping
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import .*;
import .*;
import .*;
import .*;
import .*;
public class Bounce {
public static void main(String[] args)
{
JFrame frame = new BounceFrame();
aultCloseOperation(_ON_CLOSE);
ible(true);
}
}
class BounceFrame extends JFrame
{
public BounceFrame()
{
setTitle("Bounce...");
setSize(400,450);
canvas = new BallCanvas();
Container contain = getContentPane();
(canvas,);
JPanel buttonpanel = new JPanel();
addButton(buttonpanel,"start",new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall(_PRIORITY,);
}
});
addButton(buttonpanel,"express",new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall(_PRIORITY+2,);
}
});
/*addButton(buttonpanel,"selfish",new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall(_PRIORITY+2,);
}
});*/
addButton(buttonpanel,"stop",new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
(0);
}
});
(buttonpanel,);
}
public void addButton(Container c,String name,ActionListener listener)
{
JButton button = new JButton(name);
ionListener(listener);
(button);
}
public void addBall(int priority,Color color)
{
Ball b = new Ball(canvas,color);
(b);
BallThread thread = new BallThread(b);
ority(priority);
();
}
private BallCanvas canvas;
}
/*A Thread make ball move...*/
class BallThread extends Thread
{
public BallThread(Ball aball)
{ ball = aball; }
public void run()
{
try
{
for(int i=1;i<=10000;i++)
{
();
sleep(5);
}
}
catch (InterruptedException e)
{
tThread().interrupt();
}
}
private Ball ball;
}
/*draw the ball*/
class BallCanvas extends JPanel
{
public void add(Ball b)
{
(b);
}
public void paintComponent(Graphics g)
{
omponent(g);
Graphics2D g2 = (Graphics2D)g;
for(int i=0;i<();i++)
{
Ball b = (Ball)(i);
ll(g2);
}
}
private ArrayList balls = new ArrayList();
}
class Ball
{
public Ball(Component c,Color color)
{
canvas = c;
acolor = color;
}
public void drawBall(Graphics2D g2)
{
or(acolor);
(new (x,y,15,15));
}
public void move()
{
x += dx;
y += dy;
if (x<0)
{
x = 0;
dx = -dx;
}
if (x+15 >= th())
{
x = th()-15;
dx = -dx;
}
if (y<0)
{
y = 0;
dy = -dy;
}
if (y+15 >= ght())
{
y = ght()-15;
dy = -dy;
}
t();
}
private Component canvas;
private int x = 0;
private int y = 0;
private int dx = 2;
private int dy = 2;
private Color acolor;
}