/* */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class One extends NoFlickerApplet implements MouseMotionListener, MouseListener { Circle[] circles; // array instance variable declared public void init() { circles = new Circle[400]; // allocate for (int i = 0; i < circles.length; i++) { // initialize circles[i] = new Circle( (int)(Math.random() * 600), // x (int)(Math.random() * 600), // y (int)(Math.random() * 40 + 10), // r new Color((float) Math.random(), (float) Math.random(), (float) Math.random()) ); this.addMouseMotionListener(this); this.addMouseListener(this); } } public void paint(Graphics g) { for (int i = 0; i < circles.length; i++) circles[i].draw(g); } Circle selectedCircle; public void mousePressed(MouseEvent e) { int x = e.getX(), y = e.getY(); for (int i = 0; i < circles.length; i++) { if (circles[i].contains(x, y)) { selectedCircle = circles[i]; /* return; */ } } } public void mouseDragged(MouseEvent e) { int x = e.getX(), y = e.getY(); if (selectedCircle != null) { selectedCircle.move(x, y); repaint(); } } public void mouseReleased(MouseEvent e) { selectedCircle = null; } public void mouseMoved(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } } class Circle { int x, y, radius; Color c; Circle(int x, int y, int r, Color c) { this.x = x; this.y = y; this.radius = r; this.c = c; } void draw(Graphics g) { g.setColor(this.c); g.fillOval(this.x, this.y, this.radius * 2, this.radius * 2); g.setColor(Color.black); g.drawOval(this.x, this.y, this.radius * 2, this.radius * 2); } boolean contains(int x, int y) { int xC = this.x + this.radius; int yC = this.y + this.radius; double distance = Math.sqrt((xC - x) * (xC - x) + (yC - y) * (yC - y)); return distance <= radius; } void move(int x, int y) { this.x = x - this.radius; this.y = y - this.radius; } } class NoFlickerApplet extends Applet { private Image offScreenImage; private Graphics offScreenGraphics; private Dimension offScreenSize; public final void update(Graphics theGraphicsContext){ Dimension dim = this.getSize(); /* size() originally... */ if( (offScreenImage == null) || (dim.width != offScreenSize.width) || (dim.height != offScreenSize.height)) { this.offScreenImage = this.createImage(dim.width, dim.height); this.offScreenSize = dim; this.offScreenGraphics = this.offScreenImage.getGraphics(); } this.offScreenGraphics.clearRect(0, 0, this.offScreenSize.width, this.offScreenSize.height); this.paint(offScreenGraphics); theGraphicsContext.drawImage(this.offScreenImage, 0, 0, null); } }