Serialises a Shape object. : Shape « 2D Graphics GUI « Java






Serialises a Shape object.

    

import java.awt.Shape;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 * 
 * ------------
 * IOUtils.java
 * ------------
 * (C)opyright 2002-2004, by Thomas Morgner and Contributors.
 *
 * Original Author:  Thomas Morgner;
 * Contributor(s):   David Gilbert (for Object Refinery Limited);
 *
 * $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
 *
 * Changes
 * -------
 * 26-Jan-2003 : Initial version
 * 23-Feb-2003 : Documentation
 * 25-Feb-2003 : Fixed Checkstyle issues (DG);
 * 29-Apr-2003 : Moved to jcommon
 * 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
 *               added support for query strings within these urls (TM);
 */


public class Main {
  /**
   * Returns <code>true</code> if a class implements <code>Serializable</code>
   * and <code>false</code> otherwise.
   *
   * @param c  the class.
   *
   * @return A boolean.
   */
  public static boolean isSerializable(final Class c) {
      /**
      final Class[] interfaces = c.getInterfaces();
      for (int i = 0; i < interfaces.length; i++) {
          if (interfaces[i].equals(Serializable.class)) {
              return true;
          }
      }
      Class cc = c.getSuperclass();
      if (cc != null) {
          return isSerializable(cc);
      }
       */
      return (Serializable.class.isAssignableFrom(c));
  }
  /**
   * Reads a <code>Shape</code> object that has been serialised by the
   * {@link #writeShape(Shape, ObjectOutputStream)} method.
   *
   * @param stream  the input stream (<code>null</code> not permitted).
   *
   * @return The shape object (possibly <code>null</code>).
   *
   * @throws IOException  if there is an I/O problem.
   * @throws ClassNotFoundException  if there is a problem loading a class.
   */
  public static Shape readShape(final ObjectInputStream stream)
      throws IOException, ClassNotFoundException {

      if (stream == null) {
          throw new IllegalArgumentException("Null 'stream' argument.");
      }
      Shape result = null;
      final boolean isNull = stream.readBoolean();
      if (!isNull) {
          final Class c = (Class) stream.readObject();
          if (c.equals(Line2D.class)) {
              final double x1 = stream.readDouble();
              final double y1 = stream.readDouble();
              final double x2 = stream.readDouble();
              final double y2 = stream.readDouble();
              result = new Line2D.Double(x1, y1, x2, y2);
          }
          else if (c.equals(Rectangle2D.class)) {
              final double x = stream.readDouble();
              final double y = stream.readDouble();
              final double w = stream.readDouble();
              final double h = stream.readDouble();
              result = new Rectangle2D.Double(x, y, w, h);
          }
          else if (c.equals(Ellipse2D.class)) {
              final double x = stream.readDouble();
              final double y = stream.readDouble();
              final double w = stream.readDouble();
              final double h = stream.readDouble();
              result = new Ellipse2D.Double(x, y, w, h);
          }
          else if (c.equals(Arc2D.class)) {
              final double x = stream.readDouble();
              final double y = stream.readDouble();
              final double w = stream.readDouble();
              final double h = stream.readDouble();
              final double as = stream.readDouble(); // Angle Start
              final double ae = stream.readDouble(); // Angle Extent
              final int at = stream.readInt();       // Arc type
              result = new Arc2D.Double(x, y, w, h, as, ae, at);
          }
          else if (c.equals(GeneralPath.class)) {
              final GeneralPath gp = new GeneralPath();
              final float[] args = new float[6];
              boolean hasNext = stream.readBoolean();
              while (!hasNext) {
                  final int type = stream.readInt();
                  for (int i = 0; i < 6; i++) {
                      args[i] = stream.readFloat();
                  }
                  switch (type) {
                      case PathIterator.SEG_MOVETO :
                          gp.moveTo(args[0], args[1]);
                          break;
                      case PathIterator.SEG_LINETO :
                          gp.lineTo(args[0], args[1]);
                          break;
                      case PathIterator.SEG_CUBICTO :
                          gp.curveTo(args[0], args[1], args[2],
                                  args[3], args[4], args[5]);
                          break;
                      case PathIterator.SEG_QUADTO :
                          gp.quadTo(args[0], args[1], args[2], args[3]);
                          break;
                      case PathIterator.SEG_CLOSE :
                          gp.closePath();
                          break;
                      default :
                          throw new RuntimeException(
                                  "JFreeChart - No path exists");
                  }
                  gp.setWindingRule(stream.readInt());
                  hasNext = stream.readBoolean();
              }
              result = gp;
          }
          else {
              result = (Shape) stream.readObject();
          }
      }
      return result;

  }

  /**
   * Serialises a <code>Shape</code> object.
   *
   * @param shape  the shape object (<code>null</code> permitted).
   * @param stream  the output stream (<code>null</code> not permitted).
   *
   * @throws IOException if there is an I/O error.
   */
  public static void writeShape(final Shape shape,
                                final ObjectOutputStream stream)
      throws IOException {

      if (stream == null) {
          throw new IllegalArgumentException("Null 'stream' argument.");
      }
      if (shape != null) {
          stream.writeBoolean(false);
          if (shape instanceof Line2D) {
              final Line2D line = (Line2D) shape;
              stream.writeObject(Line2D.class);
              stream.writeDouble(line.getX1());
              stream.writeDouble(line.getY1());
              stream.writeDouble(line.getX2());
              stream.writeDouble(line.getY2());
          }
          else if (shape instanceof Rectangle2D) {
              final Rectangle2D rectangle = (Rectangle2D) shape;
              stream.writeObject(Rectangle2D.class);
              stream.writeDouble(rectangle.getX());
              stream.writeDouble(rectangle.getY());
              stream.writeDouble(rectangle.getWidth());
              stream.writeDouble(rectangle.getHeight());
          }
          else if (shape instanceof Ellipse2D) {
              final Ellipse2D ellipse = (Ellipse2D) shape;
              stream.writeObject(Ellipse2D.class);
              stream.writeDouble(ellipse.getX());
              stream.writeDouble(ellipse.getY());
              stream.writeDouble(ellipse.getWidth());
              stream.writeDouble(ellipse.getHeight());
          }
          else if (shape instanceof Arc2D) {
              final Arc2D arc = (Arc2D) shape;
              stream.writeObject(Arc2D.class);
              stream.writeDouble(arc.getX());
              stream.writeDouble(arc.getY());
              stream.writeDouble(arc.getWidth());
              stream.writeDouble(arc.getHeight());
              stream.writeDouble(arc.getAngleStart());
              stream.writeDouble(arc.getAngleExtent());
              stream.writeInt(arc.getArcType());
          }
          else if (shape instanceof GeneralPath) {
              stream.writeObject(GeneralPath.class);
              final PathIterator pi = shape.getPathIterator(null);
              final float[] args = new float[6];
              stream.writeBoolean(pi.isDone());
              while (!pi.isDone()) {
                  final int type = pi.currentSegment(args);
                  stream.writeInt(type);
                  // TODO: could write this to only stream the values
                  // required for the segment type
                  for (int i = 0; i < 6; i++) {
                      stream.writeFloat(args[i]);
                  }
                  stream.writeInt(pi.getWindingRule());
                  pi.next();
                  stream.writeBoolean(pi.isDone());
              }
          }
          else {
              stream.writeObject(shape.getClass());
              stream.writeObject(shape);
          }
      }
      else {
          stream.writeBoolean(true);
      }
  }

}

   
    
    
    
  








Related examples in the same category

1.Creating Basic Shapes
2.fillRect (int, int, int, int) method draws a solid rectangle
3.Creating a Shape Using Lines and Curves
4.Combining Shapes
5.Draw rectangles, use the drawRect() method. To fill rectangles, use the fillRect() method
6.Draw lineDraw line
7.Draw a PolygonDraw a Polygon
8.Draw an oval outline
9.Draw a (Round)rectangleDraw a (Round)rectangle
10.Fill a polygonFill a polygon
11.Fill a solid oval
12.Fill a (Round)rectangleFill a (Round)rectangle
13.Change fontChange font
14.Draw rectangle 2Draw rectangle 2
15.Draw ArcDraw Arc
16.Draw EllipseDraw Ellipse
17.Fill a Rectangle 2Fill a Rectangle 2
18.Fill Arc 2Fill Arc 2
19.Draw textDraw text
20.Draw unicode string Draw unicode string
21.Shape combineShape combine
22.EffectsEffects
23.Mouse drag and drop to drawMouse drag and drop to draw
24.Arc demonstration: scale, move, rotate, sheerArc demonstration: scale, move, rotate, sheer
25.Hypnosis SpiralHypnosis Spiral
26.GlyphVector.getNumGlyphs()
27.Resize a shape
28.Rectangle with rounded corners drawn using Java 2D Graphics API
29.Compares two ellipses and returns true if they are equal or both null.
30.Compares two lines are returns true if they are equal or both null.
31.Creates a diagonal cross shape.
32.Creates a diamond shape.
33.Creates a new Stroke-Object for the given type and with.
34.Creates a region surrounding a line segment by 'widening' the line segment.
35.Creates a triangle shape that points downwards.
36.Creates a triangle shape that points upwards.
37.Generate Polygon
38.Polygon with float coordinates.
39.Polyline 2D
40.Tests two polygons for equality. If both are null this method returns true.
41.Union two rectangles
42.Calculate Intersection Clip
43.Draws a shape with the specified rotation about (x, y).
44.Checks, whether the given rectangle1 fully contains rectangle 2 (even if rectangle 2 has a height or width of zero!).
45.Reads a Point2D object that has been serialised by the writePoint2D(Point2D, ObjectOutputStream)} method.
46.Returns a point based on (x, y) but constrained to be within the bounds of a given rectangle.
47.RectListManager is a class to manage a list of rectangular regions.
48.Fill Rectangle2D.Double and Ellipse2D.DoubleFill Rectangle2D.Double and Ellipse2D.Double
49.This program demonstrates the various 2D shapesThis program demonstrates the various 2D shapes