import java.util.*;
import java.util.Random;
import java.util.List;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class bolapantul extends JFrame implements Runnable
{
private JPanel tempat = new JPanel();
private JPanel p1 = new JPanel();
private JButton bMulai = new JButton("Mulai/Tambah");
Thread thread1 = new Thread(this);
List listBola = Collections.synchronizedList(new ArrayList());
public bolapantul()
{
p1.add(bMulai);
getContentPane().add(tempat, "Center");
getContentPane().add(p1, "South");
setResizable(false);
bMulai.addActionListener(new Kejadian());
}
public class Kejadian implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
String ac = e.getActionCommand();
kelasBola bola = new kelasBola();
if(o==bMulai)
{
listBola.add(bola);
bola.start();
}
}
}
public void run()
{
Image persegi = createImage(tempat.getWidth(), tempat.getHeight());
Graphics g = persegi.getGraphics();
Graphics gc = tempat.getGraphics();
while (true)
{
g.setColor(Color.white);
g.fillRect(0, 0, tempat.getWidth(), tempat.getHeight());
synchronized (listBola)
{
for (Iterator i = listBola.iterator(); i.hasNext();)
{
kelasBola b = (kelasBola)i.next();
b.draw(g);
}
}
gc.drawImage(persegi, 0, 0, tempat);
try {Thread.sleep(5);} catch(InterruptedException e)
{
}
}
}
class kelasBola extends Thread implements Cloneable
{
private Random r;
private boolean bulat=true;
private boolean jalan=true;
private Color color = Color.black;
private int x = 0;
private int y = 0;
private int dx = 2;
private int dy = 2;
private int delay = 10;
private static final int RADIUS = 30;
public Color getWarna()
{
r=new Random();
return color=new Color((int)r.nextInt(255),(int)r.nextInt(256),(int)r.nextInt(255));
}
public void draw(Graphics g)
{
g.setColor(color);
if(bulat==true)
g.fillOval(x, y, RADIUS, RADIUS);
else
g.fillRect(x, y, RADIUS, RADIUS);
}
/**
* Updates the position of the bola, taking care of bounces.
*/
public void move()
{
x += dx;
y += dy;
if (x < 0)
{
// Bounce off left wall.
x = 0; dx = -dx;
getWarna();
}
if (x + RADIUS >= tempat.getWidth())
{
// Bounce off right wall.
x = tempat.getWidth() - RADIUS; dx = -dx;
getWarna();
}
if (y < 0)
{
// Bounce off top wall.
y = 0; dy = -dy;
getWarna();
}
if (y + RADIUS >= tempat.getHeight())
{
// Bounce off bottom wall.
y = tempat.getHeight() - RADIUS; dy = -dy;
getWarna();
}
}
public void run()
{
for (int i = 1; i <= 99999; i++)
{
move();
try {Thread.sleep(delay);} catch(InterruptedException e)
{
}
}
listBola.remove(this);
}
}
public static void main(String[] args)
{
bolapantul ujiBola1 = new bolapantul();
ujiBola1.setTitle("Bola Pantul Sederhana");
ujiBola1.setLocation(450,150);
ujiBola1.setSize(550, 450);
ujiBola1.show();
ujiBola1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ujiBola1.thread1.setPriority(Thread.MAX_PRIORITY);
ujiBola1.thread1.start();
}
}
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar