// <applet code="MovingSelection" width="400" height="400"></applet>
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
public class MovingSelection extends Applet implements Runnable {
List<TokenStore> tokens = new ArrayList<TokenStore>();
BufferedImage buffer;
Thread thread;
boolean running = false;
public void init() {
tokens.add(new TokenStore(40, 40, Color.red, 1, 3));
tokens.add(new TokenStore(140, 100, Color.green, 2, 2));
tokens.add(new TokenStore(300, 200, Color.blue, 3, 2));
tokens.add(new TokenStore(100, 325, Color.cyan, 1, 2));
tokens.add(new TokenStore(220, 250, Color.orange, 2, 3));
TokenSelector selector = new TokenSelector(this);
addMouseListener(selector);
}
public void start() {
if(!running) {
running = true;
thread = new Thread(this);
thread.start();
}
}
public void stop() {
running = false;
if(thread != null)
thread.interrupt();
thread = null;
}
public void paint(Graphics g) {
if(buffer == null) {
int w = getWidth();
int h = getHeight();
int type = BufferedImage.TYPE_INT_RGB;
buffer = new BufferedImage(w, h, type);
erase(w, h);
}
g.drawImage(buffer, 0, 0, this);
}
public void update(Graphics g) {
paint(g);
}
public void run() {
while(running) {
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}
updateBuffer();
repaint();
}
}
private void updateBuffer() {
int w = buffer.getWidth();
int h = buffer.getHeight();
erase(w, h);
Graphics2D g2 = buffer.createGraphics();
for(int j = 0; j < tokens.size(); j++) {
TokenStore token = tokens.get(j);
if(token.isVisible())
token.advance(w, h);
token.draw(g2);
}
g2.dispose();
}
private void erase(int w, int h) {
Graphics2D g2 = buffer.createGraphics();
g2.setPaint(getBackground());
g2.fillRect(0,0,w,h);
g2.dispose();
}
}
class TokenSelector extends MouseAdapter {
MovingSelection component;
public TokenSelector(MovingSelection ms) {
component = ms;
}
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
List<TokenStore> tokens = component.tokens;
for(int j = 0; j < tokens.size(); j++) {
TokenStore token = tokens.get(j);
if(token.contains(p)) {
token.select();
break;
}
}
}
}
class TokenStore {
Rectangle r = new Rectangle(20,20);
Color color;
int dx;
int dy;
boolean isVisible = true;
public TokenStore(int x, int y, Color color, int dx, int dy) {
r.setLocation(x, y);
this.color = color;
this.dx = dx;
this.dy = dy;
}
public void draw(Graphics2D g2) {
g2.setPaint(color);
if(isVisible)
g2.fill(r);
else
g2.draw(r);
}
public void advance(int w, int h) {
if(r.x + dx < 0 || r.x + r.width + dx > w)
dx *= -1;
if(r.y + dy < 0 || r.y + r.height + dy > h)
dy *= -1;
r.translate(dx, dy);
}
public void select() { isVisible = !isVisible; }
public boolean isVisible() { return isVisible; }
public boolean contains(Point p) { return r.contains(p); }
}