Thread: image removing
View Single Post
  #4 (permalink)  
Old 01-20-2008, 10:27 PM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Code:
// <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>(); 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) { g.setColor(getBackground()); g.fillRect(0,0,getWidth(), getHeight()); for(int j = 0; j < tokens.size(); j++) { TokenStore token = tokens.get(j); token.draw((Graphics2D)g); } } public void run() { while(running) { try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println(e); } for(int j = 0; j < tokens.size(); j++) { TokenStore token = tokens.get(j); token.advance(getWidth(), getHeight()); } repaint(); } } } 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)) { tokens.remove(token); break; } } } } class TokenStore { Rectangle r = new Rectangle(20,20); Color color; int dx; int dy; 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); g2.fill(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 boolean contains(Point p) { // return r.contains(p); return p.x > r.x && p.x < (r.x + r.width) && p.y > r.y && p.y < (r.y + r.height); } }
Reply With Quote