import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BallDemo extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BallDemo().setVisible(true);
}
});
}
private Game game;
private MyPanel panel;
public BallDemo() {
super("BallDemo");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton start = new JButton("Drop a ball!");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (game != null) {
game.end();
}
game = new Game();
game.start();
}
});
panel = new MyPanel(500, 500);
setLayout(new BorderLayout());
add(start, BorderLayout.NORTH);
add(panel);
pack();
setLocationRelativeTo(null);
}
class MyPanel extends JPanel {
int w, h;
public MyPanel(int w, int h) {
this.w = w;
this.h = h;
setPreferredSize(new Dimension(w, h));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (game != null) {
g.setColor(Color.RED);
g.fillOval(game.x, game.y, game.size, game.size);
}
}
}
class Game extends Thread {
boolean alive;
int size = 25;
int x = panel.w / 2 - size / 2;
int y = 0;
int factor = 5;
int dir = 1;
@Override
public void run() {
alive = true;
while (alive) {
panel.repaint();
y += dir * factor;
if (dir == 1 && y >= panel.h - size) {
dir *= -1;
factor--;
} else if (dir == -1 && y <= panel.h - (factor * 50)) {
dir *= -1;
factor--;
}
if (factor == 0) {
end();
}
try {
sleep(10);
} catch (InterruptedException e) {
}
}
}
void end() {
alive = false;
}
}
}