⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sketchview.java

📁 非常好的java事例以及带源码事例的java2教程
💻 JAVA
字号:
import javax.swing.*;
import java.util.*;                 // For Observer
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;            // For events
import javax.swing.event.*;         // For mouse input adapter
import java.awt.print.*;

class SketchView extends    JComponent
                 implements Observer, Constants, ActionListener, Printable
{
  public SketchView(Sketcher theApp)
  {
    this.theApp = theApp;
    MouseHandler handler = new MouseHandler();         // create the mouse listener
    addMouseListener(handler);                         // Listen for button events
    addMouseMotionListener(handler);                   // Listen for motion events

    // Add the pop-up menu items
    moveItem = elementPopup.add("Move");
    deleteItem = elementPopup.add("Delete");
    rotateItem = elementPopup.add("Rotate");
    sendToBackItem = elementPopup.add("Send-to-back");

    // Add the menu item listeners
    moveItem.addActionListener(this);
    deleteItem.addActionListener(this);
    rotateItem.addActionListener(this);
    sendToBackItem.addActionListener(this);
  }

  public int print(Graphics g,                     // Graphics context for printing
                 PageFormat pageFormat,            // The page format
                 int pageIndex)                    // Index number of current page
                 throws PrinterException
  {
    if(pageIndex>0)
      return NO_SUCH_PAGE;
    Graphics2D g2D = (Graphics2D) g;

    // Move origin to page printing area corner
    g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

    paint(g2D);
    return PAGE_EXISTS;
  }

  public void paint(Graphics g)
  {
    Graphics2D g2D = (Graphics2D)g;                     // Get a 2D device context
    Iterator elements = theApp.getModel().getIterator();
    Element element;                                    // Stores an element

    while(elements.hasNext())                           // Go through the list
    {
      element = (Element)elements.next();               // Get the next element
      element.draw(g2D);                                // Draw its shape
    }
  }

  // Method called by Observable object when it changes
  public void update(Observable o, Object rectangle)
  {
    if(rectangle == null)
      repaint();
    else
      repaint((Rectangle)rectangle);
  }

  private Element highlightElement;                                    // Highlighted element
  private JPopupMenu elementPopup = new JPopupMenu("Element");
  private JMenuItem moveItem, deleteItem,rotateItem, sendToBackItem;
  private Sketcher theApp;                                             // The application object
  private int mode = NORMAL;
  private Element selectedElement;

  class MouseHandler extends MouseInputAdapter
  {
    public void mousePressed(MouseEvent e)
    {
      start = e.getPoint();                    // Save cursor position
      int modifier = e.getModifiers();         // Get modifiers

      if((modifier & e.BUTTON1_MASK) != 0)
      {
            g2D = (Graphics2D)getGraphics();                 // Get graphics context
            g2D.setXORMode(getBackground());                 // Set XOR mode
            g2D.setPaint(theApp.getWindow().getElementColor()); // Set color
      }
    }

    public void mouseDragged(MouseEvent e)
    {
      last = e.getPoint();                              // Save cursor position
      int modifier = e.getModifiers();                  // Get modifiers

      if((modifier & e.BUTTON1_MASK) != 0 && 
         (theApp.getWindow().getElementType() != TEXT) &&
          (mode == NORMAL))
      {
        if(tempElement == null)                         // Is there an element?
          tempElement = createElement(start, last);     // No so create one
        else
        {
          tempElement.draw(g2D);                        // Yes - draw to erase it
          tempElement.modify(start, last);              // Modify it
        }
        tempElement.draw(g2D);                          // and draw it
      }
      else if(mode == MOVE && selectedElement != null)
      {
        selectedElement.draw(g2D);                     // Draw to erase the element
        selectedElement.move(last.x-start.x, last.y-start.y);  // Move it
        selectedElement.draw(g2D);                     // Draw in its new position
        start = last;                                  // Make start current point
      }
      else if(mode == ROTATE && selectedElement != null)
      {
        selectedElement.draw(g2D);                   // Draw to erase the element
        selectedElement.rotate(getAngle(selectedElement.getPosition(),
                                              start, last));
        selectedElement.draw(g2D);                  // Draw in its new position
        start = last;                               // Make start current point
      }
    }

    public void mouseReleased(MouseEvent e)
    {
      int modifier = e.getModifiers();                  // Get modifiers

      if(e.isPopupTrigger())
      {
        start = e.getPoint();

        if(highlightElement==null)
          theApp.getWindow().getPopup().show((Component)e.getSource(), 
                                                      start.x, start.y);
        else
          elementPopup.show((Component)e.getSource(), start.x, start.y);

        start = null;
      }

      else if((modifier & e.BUTTON1_MASK) != 0 && 
         (theApp.getWindow().getElementType() != TEXT) &&
          mode == NORMAL)
      {
        if(tempElement != null)
          theApp.getModel().add(tempElement);  // Add element to the model
      }
      else if(mode == MOVE || mode == ROTATE)
      {
        if(selectedElement != null)
          repaint();
        mode = NORMAL;
      }

      if(g2D != null)
      {
        g2D.dispose();                       // Release graphic context resource
        g2D = null;                          // Set it to null
      }
      start = last = null;                   // Remove the points
      selectedElement = tempElement = null;  // Reset elements
    }

    public void mouseClicked(MouseEvent e)
    {
      int modifier = e.getModifiers();                   // Get modifiers

      if((modifier & e.BUTTON1_MASK) != 0 && 
         (theApp.getWindow().getElementType() == TEXT))
      {

        start = e.getPoint();               // Save cursor position - start of text
        String text = JOptionPane.showInputDialog(
                   (Component)e.getSource(),              // Used to get the frame
                   "Enter Text:",                         // The message
                   "Dialog for Text Element",             // Dialog title
                   JOptionPane.PLAIN_MESSAGE);            // No icon

        if(text != null)                                  // If we have text
        {                                                 // create the element
          g2D = (Graphics2D)getGraphics();
          Font font = theApp.getWindow().getCurrentFont();

          // Create the text element
          tempElement = new Element.Text(
               font,
               text,
               start,
               theApp.getWindow().getElementColor(),
               font.getStringBounds(text, g2D.getFontRenderContext()).getBounds());

          if(tempElement != null)                         // If we created one
            theApp.getModel().add(tempElement);           // add it to the model
          tempElement = null;
          g2D.dispose();
          g2D = null;
          start = null;
        }
      }
    }

    // Handle mouse moves
    public void mouseMoved(MouseEvent e)
    {
      Point currentCursor = e.getPoint();  // Get current cursor position
      Iterator elements = theApp.getModel().getIterator();
      Element element;                                    // Stores an element

      while(elements.hasNext())                           // Go through the list
      {
        element = (Element)elements.next();               // Get the next element
        if(element.getBounds().contains(currentCursor))   // Under the cursor?
        {
          if(element==highlightElement)            // If its already highlighted
            return;                                // we are done
          g2D = (Graphics2D)getGraphics();         // Get graphics context
          if(highlightElement!=null)               // If an element is highlighted
          {
            highlightElement.setHighlighted(false);// un-highlight it and
            highlightElement.draw(g2D);            // draw it normal color
          }
          element.setHighlighted(true);            // Set highlight for new element
          highlightElement = element;              // Store new highlighted element
          element.draw(g2D);                       // Draw it highlighted 
          g2D.dispose();                       // Release graphic context resources
          g2D = null;
          return;
        }
      }

      // Here there is no element under the cursor so...
      if(highlightElement!=null)                // If an element is highlighted
      {
        g2D = (Graphics2D)getGraphics();        // Get graphics context
        highlightElement.setHighlighted(false); // ...turn off highlighting
        highlightElement.draw(g2D);             // Redraw the element
        highlightElement = null;                // No element highlighted
        g2D.dispose();                         // Release graphic context resources
        g2D = null;
      }
    }

    private Element createElement(Point start, Point end)
    {
      switch(theApp.getWindow().getElementType())
      {
        case LINE:
           return new Element.Line(start, end,
                                   theApp.getWindow().getElementColor());
        
        case RECTANGLE:
           return new Element.Rectangle(start, end,
                                        theApp.getWindow().getElementColor());
        
        case CIRCLE:
           return new Element.Circle(start, end, 
                                     theApp.getWindow().getElementColor());

        case CURVE:
         return new Element.Curve(start, end,
                                  theApp.getWindow().getElementColor());
      }
      return null;
    }

    // Helper method for calculating getAngle()
    double getAngle(Point position, Point start, Point last)
    {
      // Get perpendicular distance from last to the line from position to start
      double perp = Line2D.ptLineDist(position.x, position.y,
                                      last.x, last.y, start.x, start.y);
      // Get the distance from position to start
      double hypotenuse = position.distance(start);
      if(hypotenuse == 0.0)                        // Make sure its
        hypotenuse = 1.0;                          // non-zero

      // Angle is the arc sine of perp/hypotenuse. Clockwise is positive angle
      return -Line2D.relativeCCW(position.x, position.y,
                                 start.x, start.y,
                                 last.x, last.y)*Math.asin(perp/hypotenuse);
    }

    private Point start;                     // Stores cursor position on press
    private Point last;                      // Stores cursor position on drag
    private Element tempElement;             // Stores a temporary element
    private Graphics2D g2D;                  // Temporary graphics context
  }

  public void actionPerformed(ActionEvent e )
  {
    Object source = e.getSource();
    if(source == moveItem)
    {
      // Process a move
      mode = MOVE;
      selectedElement = highlightElement;
    }
    else if(source == deleteItem)
    {
      // Process a delete
      if(highlightElement != null)                      // If there's an element
      {
        theApp.getModel().remove(highlightElement);     // then remove it
        highlightElement = null;                        // Remove the reference
      }
    }
    else if(source == rotateItem)
    {
      // Process a rotate
      mode = ROTATE;
      selectedElement = highlightElement;
    }
    else if(source == sendToBackItem)
    {
      // Process a send-to-back
      if(highlightElement != null)
      {
        theApp.getModel().remove(highlightElement);
        theApp.getModel().add(highlightElement);
        highlightElement.setHighlighted(false);
        highlightElement = null;
        repaint();
      }
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -