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

📄 sketchframe.java

📁 JAVA 2入门经典 练习答案
💻 JAVA
📖 第 1 页 / 共 4 页
字号:

      } else if(localName.equals("color")) {
        // Should be three attributes - the RGB values
        color = new Color(Integer.parseInt(attr.getValue("R")),
                          Integer.parseInt(attr.getValue("G")),
                          Integer.parseInt(attr.getValue("B")));

      } else if(localName.equals("rectangle")) {
        // Should be one attribute - the angle
        angle = Double.parseDouble(attr.getValue("angle"));
        elementType = RECTANGLE;

      } else if(localName.equals("bottomright")) {
        bottomRight = getPoint(attr,localName);

      } else if(localName.equals("circle")) {
        // Should be two attributes - radius and angle of type double
        angle = Double.parseDouble(attr.getValue("angle"));
        radius = (int)(Double.parseDouble(attr.getValue("radius")));
        elementType = CIRCLE;

      } else if(localName.equals("curve")) {
        // Should be one attribute - the angle
        angle = Double.parseDouble(attr.getValue("angle"));
        elementType = CURVE;

      } else if(localName.equals("point")) {
        points.add(getPoint(attr, localName));

      } else if(localName.equals("text")) {
        // Should be one attribute - the angle
        angle = Double.parseDouble(attr.getValue("angle"));
        elementType = TEXT;

      } else if(localName.equals("bounds")) {
        // Should be two attributes - the width and height
        bounds = new java.awt.Rectangle(0, 0, Integer.parseInt(attr.getValue("width")),
                                              Integer.parseInt(attr.getValue("height")));

      } else if(localName.equals("font")) {
        // Should be three attributes - the font name, the font style, and the point size
        String styleStr = attr.getValue("fontstyle");
        int style = 0;

        // Figure out the style from the style attribute value
        if(styleStr.equals("bold"))
          style = Font.BOLD;
        else if(styleStr.equals("plain"))
          style = Font.PLAIN;
        else if(styleStr.equals("italic"))
          style = Font.ITALIC;
        else if(styleStr.equals("bold-italic"))
          style = Font.BOLD +Font.ITALIC;
        else
          assert false:"Error! Invalid font style.";
        
        font = new Font(attr.getValue("fontname"),       // Create the font object
                        style,
                        Integer.parseInt(attr.getValue("pointsize")));
      }
    }

    // Helper method - creates a Point object from attributes
    private Point getPoint(Attributes attr, String name) {
      return new Point((int)(Double.parseDouble(attr.getValue("x"))),
                       (int)(Double.parseDouble(attr.getValue("y"))));
    }
      
    // Creates Sketcher elements
    public void endElement(String uri, String localName, String qname) {
      // Determine what kind of element we are ending
      if(localName.equals("line")) {
        assert elementType == LINE          // Validate we have the data
               && position !=null
               && endPoint != null
               && color != null : "Error creating line";
        // Create the Line element
        Element.Line line = new Element.Line(position, endPoint, color);
        line.rotate(angle);               // Rotate it to the required angle
        xmlSketch.add(line);              // Add it to the sketch model

        // Reset data values for next time around
        resetLocalStores();
        endPoint = null;

      } else if(localName.equals("rectangle")) {
        assert elementType == RECTANGLE     // Validate we have the data
               && position !=null
               && bottomRight != null
               && color != null : "Error creating rectangle";
        Element.Rectangle rect = new Element.Rectangle(position, bottomRight, color); 
        rect.rotate(angle);               // Rotate it to the required angle
        xmlSketch.add(rect);              // Add it to the sketch model

        // Reset data values for next time around
        resetLocalStores();
        bottomRight = null;

      } else if(localName.equals("circle")) {
        assert elementType == CIRCLE      // Validate we have the data 
               && position !=null
               && radius > 0
               && color != null : "Error creating circle";
        // Convert position to circle center
        position.x += radius;
        position.y += radius;
        Element.Circle circle = new Element.Circle(position, 
                                                   new Point(position.x, position.y+radius),
                                                   color);
        circle.rotate(angle);            // Rotate it to the required angle
        xmlSketch.add(circle);           // Add it to the sketch model

        // Reset data values for next time around
        resetLocalStores();
        radius = 0;         
        
      } else if(localName.equals("curve")) {
        assert elementType == CURVE       // Validate we have the data
               && position !=null
               && points.size() > 0
               && color != null : "Error creating curve";
        // Create initial 2-point curve
        Element.Curve curve = new Element.Curve(position, (Point)(points.elementAt(0)), color);

        // Add the other points
        for(int i = 1 ; i<points.size() ; i++) 
          curve.modify(position, (Point)(points.elementAt(i)));
    
        curve.rotate(angle);             // Rotate it to the required angle
        xmlSketch.add(curve);            // Add it to the sketch model

        // Reset data values for next time around
        resetLocalStores();
        points = new Vector();
        
      } else if(localName.equals("text")) {
        assert elementType == TEXT 
               && position!=null
               && font != null
               && textStr.length() != 0
               && color != null : "Error creating curve";
        Element.Text text = new Element.Text(font, textStr.toString(),
                                              position, color, bounds);        
        text.rotate(angle);              // Rotate it to the required angle
        xmlSketch.add(text);             // Add it to the sketch model

        // Reset data values for next time around
        resetLocalStores();
        font = null;
        textStr = new StringBuffer();
        bounds = null;
      }
    }

    // Helper to reset basic data stores
    private void resetLocalStores() {
      position = null;
      color = null;
      angle = 0.0;
    }
  
    // This accumulates the text for a Text element.
    // Note that this method may be called several times for a single
    // piece of text so we assemble the text in a string buffer.
    public void characters(char[] ch, int start, int length) {
      textStr.append(ch, start, length);
    }
  
    public void error(SAXParseException spe){
      JOptionPane.showMessageDialog(SketchFrame.this,
                                    "Error at line "+spe.getLineNumber()
                                  + "\n"+spe.getMessage(),
                                    "SAX Parser Error",
                                     JOptionPane.ERROR_MESSAGE);
    }
    public void warning(SAXParseException spe){
      JOptionPane.showMessageDialog(SketchFrame.this,
                                    "Warning at line "+spe.getLineNumber()
                                  + "\n"+spe.getMessage(),
                                    "SAX Parser Warning",
                                     JOptionPane.ERROR_MESSAGE);
    }

    // Because we get data for a Sketcher element piecemeal, we need to save
    // it in these fields until we have what we need to create the element
    private SketchModel xmlSketch = null;      // The new sketch model
    private Point position = null;             // Stores an element position
    private Point endPoint = null;             // Stores line end point
    private Point bottomRight = null;          // Stores rectangle bottom right
    private Color color = null;                // Stores an element color
    private int radius = 0;                    // Stores radius of a circle
    private double angle = 0.0;                // Stores the rotation angle of an element
    Vector points = new Vector();              // Holds points for curve
    java.awt.Rectangle bounds = null;          // Bounds for a text element
    Font font = null;                          // Font for a text element 
    StringBuffer textStr = new StringBuffer(); // The text for a text element                    
  }

  // We will add inner classes defining action objects here...

  // Inner class defining the XML export action
  class XMLExportAction extends AbstractAction {
    public XMLExportAction(String name, String tooltip) {
      super(name);
      if(tooltip != null)                             // If there is tooltip text
        putValue(SHORT_DESCRIPTION, tooltip);         // ...squirrel it away
    }

    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser(DEFAULT_DIRECTORY);
        chooser.setDialogTitle("Export Sketch as XML");
        chooser.setApproveButtonText("Export");
        ExtensionFilter xmlFiles = new ExtensionFilter(".xml",
                                                      "XML Sketch files (*.xml)");
        chooser.addChoosableFileFilter(xmlFiles);             // Add the filter
        chooser.setFileFilter(xmlFiles);                      // and select it
        int result = chooser.showDialog(SketchFrame.this, null); // Show dialog
        File file = null;
        if(chooser.showDialog(SketchFrame.this, null) == chooser.APPROVE_OPTION){
          file = chooser.getSelectedFile();
          if(file.exists()) {                           // Check file exists
            if(JOptionPane.NO_OPTION ==                 // Overwrite warning
 

               JOptionPane.showConfirmDialog(SketchFrame.this,
                                  file.getName()+" exists. Overwrite?",
                                  "Confirm Save As",
                                  JOptionPane.YES_NO_OPTION,
                                  JOptionPane.WARNING_MESSAGE))
               return;                                   // No overwrite
          }
          saveXMLSketch(file);
      }
    }
  }

  // Inner class defining the XML import action
  class XMLImportAction extends AbstractAction {
    public XMLImportAction(String name, String tooltip) {
      super(name);
      if(tooltip != null)                             // If there is tooltip text
        putValue(SHORT_DESCRIPTION, tooltip);         // ...squirrel it away
    }

    public void actionPerformed(ActionEvent e) {
      JFileChooser chooser = new JFileChooser(DEFAULT_DIRECTORY);
      chooser.setDialogTitle("Import Sketch from XML");
      chooser.setApproveButtonText("Import");
      ExtensionFilter xmlFiles = new ExtensionFilter(".xml",
                                                    "XML Sketch files (*.xml)");
      chooser.addChoosableFileFilter(xmlFiles);             // Add the filter
      chooser.setFileFilter(xmlFiles);                      // and select it
      int result = chooser.showDialog(SketchFrame.this, null);  // Show dialog
      if(chooser.showDialog(SketchFrame.this, null) == chooser.APPROVE_OPTION)
        openXMLSketch(chooser.getSelectedFile());     
    }
  }

  // Inner class defining file actions
  class FileAction extends AbstractAction {    
    // Constructor
    FileAction(String name) {
      super(name);
      String iconFileName = "Images/" + name + ".gif";
      if(new File(iconFileName).exists())
        putValue(SMALL_ICON, new ImageIcon(iconFileName));
    }

   // Constructor
    FileAction(String name, KeyStroke keystroke) {
      this(name);

⌨️ 快捷键说明

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