9
SimpleSpot
- // <applet code="SimpleSpot1" width="200" height="100"></applet>
- import java.applet.Applet;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.event.*;
- public class SimpleSpot1 extends Applet implements MouseListener {
- private Spot spot = null;
- private static final int RADIUS = 15;
- private Color spotColor = new Color(107, 45, 107);
- public void init() {
- addMouseListener(this);
- }
- public void paint(Graphics g) {
- if (spot != null) {
- int radius = spot.radius;
- g.setColor(spotColor);
- g.fillOval(spot.x - radius, spot.y - radius, radius * 2, radius * 2);
- }
- }
- public void mousePressed(MouseEvent e) {
- if (spot == null)
- spot = new Spot(RADIUS);
- spot.x = e.getX();
- spot.y = e.getY();
- repaint();
- }
- public void mouseClicked(MouseEvent e) {
- }
- public void mouseReleased(MouseEvent e) {
- }
- public void mouseEntered(MouseEvent e) {
- }
- public void mouseExited(MouseEvent e) {
- }
- private class Spot {
- private int radius;
- private int x, y;
- Spot(int x, int y, int r) {
- this.radius = r;
- this.x = x;
- this.y = y;
- }
- Spot(int radius) {
- this(0, 0, radius);
- }
- }
- }
$ javac SimpleSpot1.java
$ appletviewer SimpleSpot1.java
- // <applet code="SimpleSpot2" width="200" height="100"></applet>
- import java.applet.Applet;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.RenderingHints;
- import java.awt.event.*;
- public class SimpleSpot2 extends Applet implements MouseListener {
- private Spot spot = null;
- private static final int RADIUS = 15;
- private Color spotColor = new Color(230, 182, 95);
- public void init() {
- addMouseListener(this);
- }
- public void paint(Graphics g) {
- if (spot != null)
- spot.draw(g);
- }
- public void mousePressed(MouseEvent e) {
- if (e.getButton() != MouseEvent.BUTTON1)
- return;
- if (spot == null)
- spot = new Spot(0, 0, RADIUS);
- // outer has access to inner class
- spot.x = e.getX();
- spot.y = e.getY();
- // NEVER call paint()
- repaint();
- }
- public void mouseClicked(MouseEvent e) {
- }
- public void mouseReleased(MouseEvent e) {
- }
- public void mouseEntered(MouseEvent e) {
- }
- public void mouseExited(MouseEvent e) {
- }
- private class Spot {
- private int radius;
- private int x, y;
- Spot(int x, int y, int r) {
- this.radius = r;
- this.x = x;
- this.y = y;
- }
- void draw(Graphics g) {
- // duplicate Graphics and turn it into a Graphics2D
- Graphics2D g2d = (Graphics2D) g.create();
- // turn on antialiasing for smooth painting
- g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- // inner class has access to outer class
- g2d.setColor(spotColor);
- g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
- }
- }
- }
$ javac SimpleSpot2.java
$ appletviewer SimpleSpot2.java
Comments