アニメーション処理
●サンプル
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class BallAnimation {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Ball Animation");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
class MyPanel extends JPanel implements Runnable {
all ball1, ball2;
public MyPanel() {
setBackground(Color.white);
ball1 = new Ball(100,100,2,1,0,0,280,350);
ball2 = new Ball(50,100,2,1,0,0,280,350);
Thread refresh = new Thread(this);
refresh.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
ball1.forward();
ball2.forward();
g.setColor(Color.red);
g.fillOval(ball1.getX(), ball1.getY(), 20, 20);
g.setColor(Color.blue);
g.fillOval(ball2.getX(), ball2.getY(), 20, 20);
}
public void run() {
while(true) {
repaint();
try {
Thread.sleep(10);
}
catch(Exception e) {
}
}
}
}
class Ball {
private int x;
private int y;
private int vx;
private int vy;
private int left;
private int right;
private int top;
private int bottom;
public Ball(int x, int y, int vx, int vy, int l, int t, int r, int b) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
right = r;
left = l;
top = t;
bottom = b;
}
public void forward() {
if (x + vx < left || x + vx > right)
vx = -vx;
if (y + vy < top || y + vy > bottom)
vy = -vy;
x = x + vx;
y = y + vy;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
●実行結果