Java Tutorial/2D Graphics/Mouse Draw

Материал из Java эксперт
Версия от 15:25, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Draws a small dot where the user clicks the mouse

Also reports the x, y location of the cursor and of the most recent mouse click.



/*
 *
 * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.MouseInputListener;
public class CoordinatesDemo {
  private JLabel label;
  private Point clickPoint, cursorPoint;
  private void buildUI(Container container) {
    container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
    CoordinateArea coordinateArea = new CoordinateArea(this);
    container.add(coordinateArea);
    label = new JLabel();
    resetLabel();
    container.add(label);
    coordinateArea.setAlignmentX(Component.LEFT_ALIGNMENT);
    label.setAlignmentX(Component.LEFT_ALIGNMENT); // redundant
  }
  public void updateCursorLocation(int x, int y) {
    if (x < 0 || y < 0) {
      cursorPoint = null;
      updateLabel();
      return;
    }
    if (cursorPoint == null) {
      cursorPoint = new Point();
    }
    cursorPoint.x = x;
    cursorPoint.y = y;
    updateLabel();
  }
  public void updateClickPoint(Point p) {
    clickPoint = p;
    updateLabel();
  }
  public void resetLabel() {
    cursorPoint = null;
    updateLabel();
  }
  protected void updateLabel() {
    String text = "";
    if ((clickPoint == null) && (cursorPoint == null)) {
      text = "Click or move the cursor within the framed area.";
    } else {
      if (clickPoint != null) {
        text += "The last click was at (" + clickPoint.x + ", " + clickPoint.y + "). ";
      }
      if (cursorPoint != null) {
        text += "The cursor is at (" + cursorPoint.x + ", " + cursorPoint.y + "). ";
      }
    }
    label.setText(text);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("CoordinatesDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    CoordinatesDemo controller = new CoordinatesDemo();
    controller.buildUI(frame.getContentPane());
    frame.pack();
    frame.setVisible(true);
  }
  public static class CoordinateArea extends JComponent implements MouseInputListener {
    Point point = null;
    CoordinatesDemo controller;
    Dimension preferredSize = new Dimension(400, 75);
    Color gridColor;
    public CoordinateArea(CoordinatesDemo controller) {
      this.controller = controller;
      // Add a border of 5 pixels at the left and bottom,
      // and 1 pixel at the top and right.
      setBorder(BorderFactory.createMatteBorder(1, 5, 5, 1, Color.RED));
      addMouseListener(this);
      addMouseMotionListener(this);
      setBackground(Color.WHITE);
      setOpaque(true);
    }
    public Dimension getPreferredSize() {
      return preferredSize;
    }
    protected void paintComponent(Graphics g) {
      // Paint background if we"re opaque.
      if (isOpaque()) {
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());
      }
      // Paint 20x20 grid.
      g.setColor(Color.GRAY);
      drawGrid(g, 20);
      // If user has chosen a point, paint a small dot on top.
      if (point != null) {
        g.setColor(getForeground());
        g.fillRect(point.x - 3, point.y - 3, 7, 7);
      }
    }
    // Draws a 20x20 grid using the current color.
    private void drawGrid(Graphics g, int gridSpace) {
      Insets insets = getInsets();
      int firstX = insets.left;
      int firstY = insets.top;
      int lastX = getWidth() - insets.right;
      int lastY = getHeight() - insets.bottom;
      // Draw vertical lines.
      int x = firstX;
      while (x < lastX) {
        g.drawLine(x, firstY, x, lastY);
        x += gridSpace;
      }
      // Draw horizontal lines.
      int y = firstY;
      while (y < lastY) {
        g.drawLine(firstX, y, lastX, y);
        y += gridSpace;
      }
    }
    // Methods required by the MouseInputListener interface.
    public void mouseClicked(MouseEvent e) {
      int x = e.getX();
      int y = e.getY();
      if (point == null) {
        point = new Point(x, y);
      } else {
        point.x = x;
        point.y = y;
      }
      controller.updateClickPoint(point);
      repaint();
    }
    public void mouseMoved(MouseEvent e) {
      controller.updateCursorLocation(e.getX(), e.getY());
    }
    public void mouseExited(MouseEvent e) {
      controller.resetLabel();
    }
    public void mouseReleased(MouseEvent e) {
    }
    public void mouseEntered(MouseEvent e) {
    }
    public void mousePressed(MouseEvent e) {
    }
    public void mouseDragged(MouseEvent e) {
    }
  }
}





Mouse drag and draw

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class DrawingBoardWithMatrix extends JFrame {
  public static void main(String[] args) {
    new DrawingBoardWithMatrix();
  }
  public DrawingBoardWithMatrix() {
    this.setSize(300, 300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.add(new PaintSurface(), BorderLayout.CENTER);
    this.setVisible(true);
  }
  private class PaintSurface extends JComponent {
    ArrayList<Shape> shapes = new ArrayList<Shape>();
    Point startDrag, endDrag;
    public PaintSurface() {
      this.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
          startDrag = new Point(e.getX(), e.getY());
          endDrag = startDrag;
          repaint();
        }
        public void mouseReleased(MouseEvent e) {
          Shape r = makeRectangle(startDrag.x, startDrag.y, e.getX(), e.getY());
          shapes.add(r);
          startDrag = null;
          endDrag = null;
          repaint();
        }
      });
      this.addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent e) {
          endDrag = new Point(e.getX(), e.getY());
          repaint();
        }
      });
    }
    private void paintBackground(Graphics2D g2){
      g2.setPaint(Color.LIGHT_GRAY);
      for (int i = 0; i < getSize().width; i += 10) {
        Shape line = new Line2D.Float(i, 0, i, getSize().height);
        g2.draw(line);
      }
      for (int i = 0; i < getSize().height; i += 10) {
        Shape line = new Line2D.Float(0, i, getSize().width, i);
        g2.draw(line);
      }
      
    }
    public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      paintBackground(g2);
      Color[] colors = { Color.YELLOW, Color.MAGENTA, Color.CYAN , Color.RED, Color.BLUE, Color.PINK};
      int colorIndex = 0;
      g2.setStroke(new BasicStroke(2));
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));
      for (Shape s : shapes) {
        g2.setPaint(Color.BLACK);
        g2.draw(s);
        g2.setPaint(colors[(colorIndex++) % 6]);
        g2.fill(s);
      }
      if (startDrag != null && endDrag != null) {
        g2.setPaint(Color.LIGHT_GRAY);
        Shape r = makeRectangle(startDrag.x, startDrag.y, endDrag.x, endDrag.y);
        g2.draw(r);
      }
    }
    private Rectangle2D.Float makeRectangle(int x1, int y1, int x2, int y2) {
      return new Rectangle2D.Float(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2));
    }
  }
}





Save Your Drawing To a File

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SaveYourDrawingToFile extends JFrame implements MouseListener, ActionListener {
  List<Point> displayList = new ArrayList<Point>();
  String pathname = "data.dat";
  JButton clearBtn = new JButton("Clear");
  JButton saveBtn = new JButton("Save");
  JButton restoreBtn = new JButton("Restore");
  JButton quitBtn = new JButton("Quit");
  public static void main(String args[]) {
    SaveYourDrawingToFile that = new SaveYourDrawingToFile();
    that.setVisible(true);
  }
  public SaveYourDrawingToFile() {
    addMouseListener(this);
    setLayout(new BorderLayout());
    Panel pan = new Panel();
    clearBtn.addActionListener(this);
    pan.add(clearBtn);
    saveBtn.addActionListener(this);
    pan.add(saveBtn);
    restoreBtn.addActionListener(this);
    pan.add(restoreBtn);
    quitBtn.addActionListener(this);
    pan.add(quitBtn);
    add("North", pan);
    setSize(350, 200);
  }
  public void paint(Graphics g) {
    g.setColor(Color.white);
    g.fillRect(0, 0, getSize().width, getSize().height);
    g.setColor(Color.black);
    int i = 0;
    while (i < displayList.size()) {
      Point p0 = (Point) (displayList.get(i++));
      Point p1 = (Point) (displayList.get(i++));
      int x = Math.min(p0.x, p1.x);
      int y = Math.min(p0.y, p1.y);
      int w = Math.abs(p0.x - p1.x);
      int h = Math.abs(p0.y - p1.y);
      g.drawRect(x, y, w, h);
    }
  }
  public void mousePressed(MouseEvent e) {
    Point p = new Point(e.getX(), e.getY());
    displayList.add(p);
  }
  public void mouseReleased(MouseEvent e) {
    Point p = new Point(e.getX(), e.getY());
    displayList.add(p);
    repaint();
  }
  public void mouseClicked(MouseEvent e) {
  }
  public void mouseEntered(MouseEvent e) {
  }
  public void mouseExited(MouseEvent e) {
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clearBtn) {
      displayList = new Vector();
      repaint();
    } else if (e.getSource() == saveBtn) {
      try {
        FileOutputStream fos = new FileOutputStream(pathname);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(displayList);
        oos.flush();
        oos.close();
        fos.close();
      } catch (Exception ex) {
        System.out.println("Trouble writing display list vector");
      }
    } else if (e.getSource() == restoreBtn) {
      try {
        FileInputStream fis = new FileInputStream(pathname);
        ObjectInputStream ois = new ObjectInputStream(fis);
        displayList = (Vector) (ois.readObject());
        ois.close();
        fis.close();
        repaint();
      } catch (Exception ex) {
        System.out.println("Trouble reading display list vector");
      }
    } else if (e.getSource() == quitBtn) {
      setVisible(false);
      dispose();
      System.exit(0);
    }
  }
}





Select the Ellipse to Move It in the Canvas

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
public class CircleWithHandles extends JFrame {
  DrawingCanvas canvas = new DrawingCanvas();
  public CircleWithHandles() {
    getContentPane().add(canvas);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  }
  public static void main(String arg[]) {
    new CircleWithHandles();
  }
  class DrawingCanvas extends Canvas {
    double x = 20, y = 20, w = 50, h = 50;
    int x1, y1, x2, y2;
    Ellipse2D ellipse;
    Ellipse2D selectedShape;
    Rectangle2D handleRectangle;
    Cursor curCursor;
    public DrawingCanvas() {
      setBackground(Color.white);
      addMouseListener(new MyMouseListener());
      addMouseMotionListener(new MyMouseMotionListener());
      setSize(400, 300); 
    }
    public void paint(Graphics g) {
      Graphics2D g2D = (Graphics2D) g;
      ellipse = new Ellipse2D.Double(x, y, w, h);
      g2D.draw(ellipse);
      if (handleRectangle != null) {
        drawHighlightSquares(g2D, handleRectangle);
      }
      if (curCursor != null)
        setCursor(curCursor);
    }
    public void drawHighlightSquares(Graphics2D g2D, Rectangle2D r) {
      double x = r.getX();
      double y = r.getY();
      double w = r.getWidth();
      double h = r.getHeight();
      g2D.setColor(Color.black);
      g2D.fill(new Rectangle.Double(x - 3.0, y - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x + w * 0.5 - 3.0, y - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x + w - 3.0, y - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x - 3.0, y + h * 0.5 - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x + w - 3.0, y + h * 0.5 - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x - 3.0, y + h - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x + w * 0.5 - 3.0, y + h - 3.0, 6.0, 6.0));
      g2D.fill(new Rectangle.Double(x + w - 3.0, y + h - 3.0, 6.0, 6.0));
    }
    class MyMouseListener extends MouseAdapter {
      public void mousePressed(MouseEvent e) {
        if (ellipse.contains(e.getX(), e.getY())) {
          selectedShape = ellipse;
          if (handleRectangle != null)
            handleRectangle = ellipse.getBounds2D();
        } else {
          handleRectangle = null;
        }
        canvas.repaint();
        x1 = e.getX();
        y1 = e.getY();
      }
      public void mouseReleased(MouseEvent e) {
        if (ellipse.contains(e.getX(), e.getY())) {
          handleRectangle = ellipse.getBounds2D();
          selectedShape = ellipse;
        }
        canvas.repaint();
      }
      public void mouseClicked(MouseEvent e) {
        if (ellipse.contains(e.getX(), e.getY())) {
          selectedShape = ellipse;
          handleRectangle = ellipse.getBounds2D();
        } else {
          if (handleRectangle != null)
            handleRectangle = null;
        }
        canvas.repaint();
      }
    }
    class MyMouseMotionListener extends MouseMotionAdapter {
      public void mouseDragged(MouseEvent e) {
        if (ellipse.contains(e.getX(), e.getY())) {
          handleRectangle = null;
          selectedShape = ellipse;
          x2 = e.getX();
          y2 = e.getY();
          x = x + x2 - x1;
          y = y + y2 - y1;
          x1 = x2;
          y1 = y2;
        }
        canvas.repaint();
      }
      public void mouseMoved(MouseEvent e) {
        if (ellipse != null) {
          if (ellipse.contains(e.getX(), e.getY())) {
            curCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
          } else {
            curCursor = Cursor.getDefaultCursor();
          }
        }
        canvas.repaint();
      }
    }
  }
}





The SimpleDraw application

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class SimpleDraw extends JFrame
        implements ActionListener, MouseListener {
    // (x1,y1) = coordinate of mouse pressed
    // (x2,y2) = coordinate of mouse released
    int x1;
    int y1;
    int x2;
    int y2;
    ArrayList<Shape> shapes = new ArrayList<Shape>();
    String shapeType = "Rectangle";
    public SimpleDraw() {
        this.setTitle("Simple DRAW");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // add check box group
        ButtonGroup cbg = new ButtonGroup();
        JRadioButton lineButton = new JRadioButton("Line");
        JRadioButton ovalButton = new JRadioButton("Oval");
        JRadioButton rectangleButton =
                new JRadioButton("Rectangle");
        cbg.add(lineButton);
        cbg.add(ovalButton);
        cbg.add(rectangleButton);
        lineButton.addActionListener(this);
        ovalButton.addActionListener(this);
        rectangleButton.addActionListener(this);
        rectangleButton.setSelected(true);
        JPanel radioPanel = new JPanel(new FlowLayout());
        radioPanel.add(lineButton);
        radioPanel.add(ovalButton);
        radioPanel.add(rectangleButton);
        this.addMouseListener(this);
        this.setLayout(new BorderLayout());
        this.add(radioPanel, BorderLayout.NORTH);
    }
    public void paint(Graphics g) {
        paintComponents(g);
        for (Shape shape : shapes) {
          Graphics2D g2 = (Graphics2D)g;  
          g2.draw(shape);
        }
    }
    public void actionPerformed(ActionEvent ae) {
        shapeType = ae.getActionCommand().toString();
    }
    public void mouseClicked(MouseEvent me) {
    }
    public void mouseEntered(MouseEvent me) {
    }
    public void mouseExited(MouseEvent me) {
    }
    public void mousePressed(MouseEvent me) {
        x1 = me.getX();
        y1 = me.getY();
    }
    public void mouseReleased(MouseEvent me) {
        x2 = me.getX();
        y2 = me.getY();
        Shape shape = null;
        if (shapeType.equals("Rectangle")) {
            // a Rectangle cannot have a zero width or height
            if (x1 != x2 || y1 != y2) {
                shape = new Rectangle(x1, y1, x2, y2);
            }
        } 
        if (shape != null) {
            this.shapes.add(shape);
            this.repaint();
        }
    }
    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        SimpleDraw frame = new SimpleDraw();
        frame.pack();
        frame.setVisible(true);
    }
}