Shape program

Please Help Me to understand thes erors
this is the program
public class CreateObjectDemo {
public static void main(String[] args) {
//Declare and create a point object
//and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
//display rectOne's width, height, and area
System.out.println("Width of rectOne: " +
rectOne.width);
System.out.println("Height of rectOne: " +
rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());
//set rectTwo's position
rectTwo.origin = originOne;
//display rectTwo's position
System.out.println("X Position of rectTwo: "
+ rectTwo.origin.x);
System.out.println("Y Position of rectTwo: "
+ rectTwo.origin.y);
//move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: "
+ rectTwo.origin.x);
System.out.println("Y Position of rectTwo: "
+ rectTwo.origin.y);
this is the Command promptMicrosoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Kenneth Rinderhagen>cd C:\
C:\>javac CreateObjectDemo.java
CreateObjectDemo.java:7: cannot find symbol
symbol : class Point
location: class CreateObjectDemo
Point originOne = new Point(23, 94);
^
CreateObjectDemo.java:7: cannot find symbol
symbol : class Point
location: class CreateObjectDemo
Point originOne = new Point(23, 94);
^
CreateObjectDemo.java:8: cannot find symbol
symbol : class Rectangle
location: class CreateObjectDemo
Rectangle rectOne = new Rectangle(originOne, 100, 200);
^
CreateObjectDemo.java:8: cannot find symbol
symbol : class Rectangle
location: class CreateObjectDemo
Rectangle rectOne = new Rectangle(originOne, 100, 200);
^
CreateObjectDemo.java:9: cannot find symbol
symbol : class Rectangle
location: class CreateObjectDemo
Rectangle rectTwo = new Rectangle(50, 100);
^
CreateObjectDemo.java:9: cannot find symbol
symbol : class Rectangle
location: class CreateObjectDemo
Rectangle rectTwo = new Rectangle(50, 100);
^
6 errors
C:\>
Please Kenneth Rinderhagen
[email protected]

C:\>javac CreateObjectDemo.java
CreateObjectDemo.java:1: class, interface, or enum expected
importjava.awt.point;
^
CreateObjectDemo.java:2: class, interface, or enum expected
importjava.awt.Rectangle;
^
2 errors
C:\>should be
import java.awt.Point; //not importjava...p<-- should be P
import java.awt.Rectangle; //not importjava...

Similar Messages

  • Trouble looping

    Hi, I've been given a crash course in java but now have to complete a random shapes program and I have 2 main problems - I've managed to create an infinite loop and I appear to expect two entries of shape name instead of one. I'm baffled and have been staring at this for ten hours - at this stage I think I'm making it worse. Any help would be greatly appreciated.
    import java.util.Random;
    import java.lang.*;
    public class Tester {
      private static RandomShapeGenerator gen = new RandomShapeGenerator();
      public static void printMenu(){
           System.out.println("Please choose one of the following options ");
           System.out.println("1. Show shapes details                     ");
           System.out.println("2. Modify shape dimensions                 ");
           System.out.println("3. Modify shape colour                 ");
           System.out.println("4. Move shape to a location                 ");
           System.out.println("5. Exit                           ");
           System.out.println("*******************************************");
      public static String checkTypeOfObject(Object obj){//instance of an object- review notes
         if (obj instanceof Circle)
              return "Circle";
        else if (obj instanceof Square)
             return "Square";
         else if(obj instanceof Rectangle)
              return "Rectangle";
        else if(obj instanceof Ellipse)
              return "Ellipse";
        else if(obj instanceof Triangle)
              return "Triangle";
         else
              return "";
         public static void main(String[] args) {
         boolean done = false;
         int userOption;
         System.out.println("*******************************************");
         System.out.println("**   Shape Project    **                   ");
         System.out.println("* Author:              *                   ");
         System.out.println("*******************************************");
         System.out.println("About to Create random Shapes... Please wait...\n\n");
             {     Shape[] s = new Shape[5];
        // Fill up the array with shapes:
        for (int i = 0; i < s.length; i++)
          s[i] = gen.next();
        // Make polymorphic method calls:
        for (int i = 0; i < s.length; i++)
          s.getMyDetails();
    while(!done){System.out.println("Please Enter name of shape you wish to modify or view: ");
        String shapeName=Console.readString();
           Shape shapeToModify;
        boolean found =false;
             if(!found)
         System.out.println("**   Shape NOT Found   **");
       for (int j=0; j < s.length; j++){
          shapeToModify =s[j];
    shapeName = shapeToModify.getName();
         if(shapeName.equalsIgnoreCase(shapeName.trim())){
              System.out.println("** Shape Found **");
              found =true;
         printMenu();
              userOption = Console.readInt();
         //try{
              if (userOption == 5)
                   done = true;
    { System.out.println("**   Exiting... **");     
                   System.out.println("** Goodbye **");
                   if(userOption == 1)
                   { shapeToModify.getMyDetails();
              else if (userOption == 2)      
         { if(checkTypeOfObject(shapeToModify).equals("Circle"))
         {System.out.print("Please enter the radius: ");
                    double Input = Console.readDouble();
                    Circle circle1 =(Circle)shapeToModify;
                     circle1.setRadius(Input);
                     System.out.print("Sucessfully changed dimensions of circle : Details are ..\n ");
                    circle1.getMyDetails();
                    userOption = 0;
         if(checkTypeOfObject(shapeToModify).equals("Square"))
         {System.out.print("Please enter the length: ");
                     Double length = Console.readDouble();
                     //System.out.print("Please enter the width: ");
                     //String width = Console.readDouble();
                    Square square1 =(Square)shapeToModify;
                     square1.setLength(length);
                     //square1.setWidth((new Double(width).doubleValue()));
                     System.out.print("Sucessfully changed dimensions of square : Details are ..\n ");
                     square1.getMyDetails();
         if(checkTypeOfObject(shapeToModify).equals("Rectangle"))
         {System.out.print("Please enter the length: ");
                     Double length = Console.readDouble();
                     System.out.print("Please enter the width: ");
                     Double width = Console.readDouble();
                    Rectangle rectangle1 =(Rectangle)shapeToModify;
                     rectangle1.setwidth(length);
                     rectangle1.setHeight(width);
                     System.out.print("Sucessfully changed dimensions of rectangle : Details are ..\n ");
                     rectangle1.getMyDetails();
         if(checkTypeOfObject(shapeToModify).equals("Triangle"))
         {System.out.print("Please enter the length: ");
                     Double length = Console.readDouble();
                     System.out.print("Please enter the height: ");
                     Double height = Console.readDouble();
                     System.out.print("Please enter the width: ");
                     Double width = Console.readDouble();
                    Triangle triangle1 =(Triangle)shapeToModify;
                     triangle1.setLength(length);
                     triangle1.setHeight(height);
                     triangle1.setWidth(width);     
                     System.out.print("Sucessfully changed dimensions of triangle : Details are ..\n ");
                     triangle1.getMyDetails();
         if(checkTypeOfObject(shapeToModify).equals("Ellipse"))
         {System.out.print("Please enter the MajorAxis: ");
                     Double semiMajorAxis = Console.readDouble();
                     System.out.print("Please enter the MinorAxis: ");
                     Double semiMinorAxis = Console.readDouble();
                    Ellipse ellipse1 =(Ellipse)shapeToModify;
                     ellipse1.setSemiMajorAxis(semiMajorAxis);
                     ellipse1.setSemiMinorAxis(semiMinorAxis);
                     System.out.print("Sucessfully changed dimensions of triangle : Details are ..\n ");
                     ellipse1.getMyDetails();
              else if (userOption == 3)
              { System.out.print("Please enter a colour: ");      
                   String colour = Console.readString();
              shapeToModify.setColour(colour.trim());
              System.out.print("Sucessfully changed dimensions : Details are ..\n ");
         shapeToModify.getMyDetails();
              else if (userOption == 4)
                   System.out.print("Please enter the xCooridinate: ");
         int x = Console.readInt();
         System.out.print("Please enter the yCoordinate: ");
         int y = Console.readInt();
         Coordinate coordinate =shapeToModify.getLocation();
         coordinate.setXCoOrdinate(x);
              coordinate.setYCoOrdinate(y);
              System.out.print("Sucessfully changed coordinate : Details are ..\n ");
         shapeToModify.getMyDetails();
              else if ((1 < userOption) | (userOption > 5));
              { System.out.println("Sorry, that is not a valid value. Please try again.");
    /*catch(Exception ex)
              System.out.println("ERROR - Exiting....");     }
    class RandomShapeGenerator {
    private Random rand = new Random();
    private String[] names =new String[]{"Shape1","Shape2","Shape3","Shape4","Shape5"};
    private String[] colours =new String[]{"white","red","indigo","black","purple"};
    private double[] widthArray =new double[]{10.00,11.00,12.00,13.00,14.00,15.00};
    private double[] heightArray =new double[]{10.00,11.00,12.00,13.00,14.00,15.00};
    private double[] lengthArray =new double[]{10.00,11.00,12.00,13.00,14.00,15.00};
    private double[] radiusArray =new double[]{10.00,11.00,12.00,13.00,14.00,15.00};
    private double[] majorAxisArray =new double[]{10.00,11.00,12.00,13.00,14.00,15.00};
    private double[] minorAxisArray =new double[]{10.00,11.00,12.00,13.00,14.00,15.00};
    public Shape next() {
         switch (rand.nextInt(5)) {
         default:
         case 0:
         return new Circle(radiusArray[2],names[5],colours[3],new Coordinate(0,0));
         case 1:
         return new Square(lengthArray[1], widthArray[2],names[1],colours[1],new Coordinate(0,0));
         case 2:
         return new Triangle(lengthArray[2],heightArray[2],widthArray[3],names[2],colours[2],new Coordinate(0,0));
         case 3:
              return new Rectangle (lengthArray[3],heightArray[3],names[0],colours[0],new Coordinate(0,0));
         case 4:
         return new Ellipse (majorAxisArray[4],minorAxisArray[4],names[4],colours[4],new Coordinate(0,0));

    I can't seem to duplicate the read error but this will show you what I mean about the shape name. The array that creates shapes calls them "Shape1" to "Shape5". This says 'shape found' for anything you type in. I'm sure I'm doing something silly but I can't see it.
    public class errors {
    private static RandomShapeGenerator gen = new RandomShapeGenerator();
         public static void main(String[] args) {
         boolean done = false;
         int userOption;
             {     Shape[] s = new Shape[5];
        // Fill up the array with shapes:
        for (int i = 0; i < s.length; i++)
          s[i] = gen.next();
        // Make polymorphic method calls:
        for (int i = 0; i < s.length; i++)
          s.getMyDetails();
    {System.out.println("Please Enter name of shape you wish to modify or view: ");
        String shapeName=Console.readString();
           Shape shapeToModify;
        boolean found =false;
        //     if(!found)
       for (int j=0; j < s.length; j++){
          shapeToModify =s[j];
    shapeName = shapeToModify.getName();
         if(shapeName.equalsIgnoreCase(shapeName.trim())){
              System.out.println("** Shape Found **");
              found =true;}
              else {System.out.println("**   Shape NOT Found   **");
                   break;}
         printMenu();
              userOption = Console.readInt();
                   if(userOption == 1)
                   { shapeToModify.getMyDetails();

  • Keyframe for Bezier Point?

    Hello,
    Is it not possible in Motion to add or remove points during a vector animated mask (that changes shapes)?
    If not, any suggestions of a workaround? I need to make this big curley-q shape build in following the shape of the curley-q... so it starts out simple and gets real hairy. It would be great if I could add points as it goes, but that doesn't seem to work?
    Thanks!

    This is the case with all bezier shape programs I've used. Your best bet may be to set your shape on the most complex, then work backwards...
    Patrick

  • Does TR line card (ASR9K) support H-QoS?

    Hi,
    I have some question regarding on the 2nd generation line card for ASR9k.
    Line Card Types
    The Cisco ASR 9000 Series line cards are available in Service Edge Optimized and Packet Transport Optimized variants.
    • Service Edge Optimized (SE) line cards are designed for customer deployments requiring enhanced quality of service (QoS).
    • Packet Transport Optimized (TR) line cards are designed for network deployments where basic QoS is required.
    Different line card types may be mixed within the same system.
    I already review ASR9k presentation from Xander-Thuijs and found that
    SE line card support 256K queues/NP
    TR line card support 8 queues/Port
    I'm not sure whether TR line card support H-QoS.
    Could you please give more clarification about this?
    Br,
    Pipatpong

    HEre is an example:
    RP/0/RSP0/CPU0:A9K-BNG#show qos int g 0/0/0/0 out
    Sun Oct 13 13:31:19.867 EDT
    Interface: GigabitEthernet0_0_0_0 output
    Bandwidth configured: 200000 kbps Bandwidth programed: 200000 kbps
    ANCP user configured: 0 kbps ANCP programed in HW: 0 kbps
    Port Shaper programed in HW: 200000 kbps
    Policy: xtp Total number of classes: 4
    Level: 0 Policy: xtp Class: class-default
    QueueID: N/A
    Shape CIR : NONE
    Shape PIR Profile : 0/4(S) Scale: 195 PIR: 199680 kbps  PBS: 2496000 bytes
    WFQ Profile: 0/9 Committed Weight: 10 Excess Weight: 10
    Bandwidth: 0 kbps, BW sum for Level 0: 0 kbps, Excess Ratio: 1
    Level: 1 Policy: xt Class: m1
    Parent Policy: xtp Class: class-default
    QueueID: 136 (Priority 1)
    Queue Limit: 4 kbytes Abs-Index: 4 Template: 0 Curve: 6
    Shape CIR Profile: INVALID
    Policer Profile: 53 (Single)
    Conform: 296 kbps (300 kbps) Burst: 3750 bytes (0 Default)
    Child Policer Conform: TX
    Child Policer Exceed: DROP
    Child Policer Violate: DROP
    Level: 1 Policy: xt Class: m2
    Parent Policy: xtp Class: class-default
    QueueID: 137 (Priority 2)
    Queue Limit: 8 kbytes Abs-Index: 6 Template: 0 Curve: 6
    Shape CIR Profile: INVALID
    Policer Profile: 54 (Single)
    Conform: 600 kbps (600 kbps) Burst: 7500 bytes (0 Default)
    Child Policer Conform: TX
    Child Policer Exceed: DROP
    Child Policer Violate: DROP
    Level: 1 Policy: xt Class: class-default
    Parent Policy: xtp Class: class-default
    QueueID: 138 (Priority Normal)
    Queue Limit: 2496 kbytes Abs-Index: 89 Template: 0 Curve: 0
    Shape CIR Profile: INVALID
    WFQ Profile: 0/9 Committed Weight: 10 Excess Weight: 10
    Bandwidth: 0 kbps, BW sum for Level 1: 0 kbps, Excess Ratio: 1
    This class default will get reused by other interaces very likely unless you have a bw remaining (percent) in there.
    So every time you see a unique QueueID you burn a queue.
    the reason why the parent shaper at level 0 says N/A is because this is a hierarchical pmap and is shaping the overal chuld classes inclduing class-default.
    So in this example applying this pmap multiple times will burn queues for class-default.
    In other words, this Pmap example uses 3 queues. One for the shaper (child class-default) and 2 PQ's of prio's 1 and 2).
    policy-map xtp
    class class-default
      service-policy xt
      shape average 200 mbps
    end-policy-map
    RP/0/RSP0/CPU0:A9K-BNG#sh run policy-map xt
    Sun Oct 13 13:34:45.049 EDT
    policy-map xt
    class m1
      priority level 1
      police rate 300 kbps
    class m2
      priority level 2
      police rate 600 kbps
    class class-default
    end-policy-map

  • How can I select same color shapes in adobe flash program ?

    how can I select same color shapes in adobe flash program ? for example we assume 10 rectangle shapes . 3 of them are red others are green. I want to use only one click or method to select 3 of them. please help me
    thanks kunter

    that is not possible unless they are all grouped into one symbol or movieclip

  • Could not complete the define custom shape command because of program error

    I am using the pen tool to draw a shape and then select it to create a custom shape. I use path: edit - define custom shape = "could not complete the define custom shape command because of program error"
    The error message appears once I click the define button.

    Also, I solved this another way, seems to happen to me often. I click on the path panel, near layers panel and clicked on 'load path as a selection' (3rd icon on bottom from left), then click 'make work path from selection' (4th icon on bottom from left). Then you will see that the whole work area is part of the selection, including your desired shape/path. In order to change this, just select 'path selection' tool and highlight each corner and delete each point from each corner, then you are left with the desired selection to create a shape. I am self taught and this seem unorthodox, but it works.

  • When I click on Define Custom Shape, I get an error message: "could not complete your request because of a program error."

    I'm using Photoshop CC 2014. When I click on Define Custom Shape, there is an error box that says "could not complete your request because of a program error."  How can I solve this problem or work around it? I've looked on the internet for answers but could find no solutions to this. The custom shape tool is 99% of what I use!

    Consider resetting the Pen tool by right clicking here
    and if that doesn't solve the problem a logical next step would be to reset your Preferences.
    To reset Preferences:
    If Photoshop is already open on your screen, close it (Quit). Then hold down Shift+Ctrl+Alt (Win) / Shift+Command+Option (Mac) on your keyboard and start Photoshop.
    A dialog box will pop up asking if you want to delete the existing Preferences file (the "Settings"). Click Yes in the dialog box. The existing Preferences file will be scrapped and a new one will be created.
    By the way, if "The custom shape tool is 99% of what I use!" have you considered Illustrator?

  • 3d Mapping a shape with a raster image. Another program?

    Hey all. So, like the title suggests, I'm trying to make a raster file look 3d, say like adding a texture to a drapery, or picture to a guy's shirt.. lots of curves. I thought meshing, but it seems that's only for color, and not symbols. I also thought maybe there's a plug-in for Photoshop. And if neither, does Adobe make a 3d modeling program I could use?
    Thanks,
    Kaleb

    Mesh Envelopes can distort raster images. You would then add other objects to create the shading. You can do quite convincing renderings this way, but it's rather tedious.
    3D Effect can map raster images to its model surfaces, and shade them; but it is limited to simple extrusions and lathes; so it's more suited to shape primitives, not really practical for surfaces with folds
    and irregular compound curves.
    JET

  • I get program error for shape tool and color selection, any clues please?

    Hi, I cannot use my colour selection or my shape tool. I get a 'program error' pop-up. Can anyone help me with this please?

    mikem
    Go to Edit Menu/Preferences/Audio Hardware and ASIO tab and click on it.
    Under the Input tab, make sure that you have your microphone selected.
    Please let us know the outcome.
    Thank you.
    ATR

  • I would like to find a program to draw lines, shapes and words for my iMac.

    If anyone can help me find a program or App for my iMac that lets me draw lines, shapes and letters.
         Thank You
         Sandy

    http://www.sketchup.com/
    Try this it is a free download and it is a great program. I almost feel guilty not paying anything:)

  • Photoshop CS2 not working after 10.6.7 update? program error!

    Could not complete your request because of a program error. I opened an image RGB and wanted to save it as a CMYK.
    Save as and entered new name... thats it! Then the error popped up. The only thing that has changed is the update!
    Please help.

    If you updated to 10.6.7 then you should (go to your Apple menu at the far left and) check for updates.
    There was a problem with some types of Fonts that has been fixed by the Snow Leopard Font update:
    http://support.apple.com/kb/DL1377
    However, always wait after an OS update (true of Windows too) and see if it causes any problems with 3rd-party software, etc. - PRIOR to updating your system   And always, always have a full, known-good backup before you update. Especially for any computer that is used for business purposes !
    Last but definitely not least, you should know that Adobe CS2 is a Power-PC only application (circa G4 and G5 processors, before Apple moved to Intel processors), and requires Rosetta (PowerPC emulation).
    So you should consider any CS2 application running at all, as fairly miraculous.
    CS3 was released four years ago, and provided the first Intel-native ("Universal Binary") versions of the CS-suite applications.
    Mac OS 10.6 only runs on Intel-based Macs (ie: Intel processor required).
    If you are using Photoshop CS2 for any revenue-generating purposes, then it is (and was) incumbent upon you to properly allocate and budget for
    upgrades and you should - nay, must - be running a more current version of the software. If your budget does not allow for newer Adobe CS, then you should have kept a legacy system that can run an older Mac OS, and understand that your workflow is living on borrowed time - and you had best keep several old Macs that can still run an older Mac OS and run your CS2 natively.
    In no way shape or form is CS2 supported under Mac OS X 10.6 - certainly not in any official way by Adobe !
    You could also be irate about not being able to use your 8-track tape player in your brand new car. I'm exaggerating but not too much.
    Please read Adobe's response regarding CS3 (not CS2) and 10.6/Snow Leopard:
    http://blogs.adobe.com/jnack/2009/08/adobe_snow_leopard_faq.html
    With all of this in mind, you should know that your frustrations with Apple and the unsupported and not-recommended interaction of CS2 and 10.6 are misguided. Best of luck to you !

  • Programming a Pencil Tool on Paint?

    Here's my code for Scribble(a pencil tool) and its superclass Shape. Basically, my program remembers where the mouse has been and draws a line from the previous point to the current point. However, the scribble doesn't show up (occasionally you will see a small line at the very end) I think the problem is that each Scribble object only has one previous and one current. Therefore, there is only 1 line left at the end. How can I correct this?
    Thanks in advance!
    Note: this doesn't run since there are about 5 other classes needed. I guess can post them if you want? xD
    import java.awt.*;
    public class Scribble extends Shape{
         protected Point startpt, endpt;
         protected Point previous, current;
         int count = 0;
        public Scribble(Point start, DrawingCanvas dcanvas){
         super();
         System.out.println("SCRIBBLE CREATED!!!!!!!\n\n");
         startpt = start;
         current = start;
         endpt = start;
         canvas = dcanvas;
         bounds = new Rectangle(start);
        public void resize(Point anchor, Point end){
         super.resize(anchor, end);
         previous = current;
         startpt = anchor;
         current = end;
         endpt = end;
        public void translate(int dx, int dy){
         super.translate(dx, dy);
         previous.translate(dx, dy);
         current.translate(dx, dy);
         startpt.translate(dx, dy);
         endpt.translate(dx, dy);
        public void draw(Graphics g, Rectangle regionToDraw){
              count++;
              System.out.println(count);
         if (!bounds.intersects(regionToDraw)){
             return;
         g.setColor(super.getColor());
         g.drawLine((int)previous.getX(), (int)previous.getY(), (int)current.getX(), (int)current.getY());
         if (isSelected) { // if selected, draw the resizing knobs
                           // along the 4 corners
             Rectangle[] knobs = getKnobRects();
             for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs.x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[2];
         knobs[0] = new Rectangle((int)startpt.getX() - KNOB_SIZE/2,
                        (int)startpt.getY() - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[1] = new Rectangle((int)endpt.getX() - KNOB_SIZE/2,
                        (int)endpt.getY()- KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         return knobs;
    protected int getKnobContainingPoint(Point pt){
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    }import java.awt.*;
    import java.util.*;
    import java.io.*;
    public abstract class Shape implements Serializable, Cloneable{
         private Color color;
    protected Rectangle bounds;
    protected boolean isSelected;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
         Shape(){
              color = Color.darkGray;
         public Color getColor(){
         return color;
         public Object clone(){
              try{
              Shape copy = (Shape)super.clone();
              copy.setBounds(bounds);
              return copy;
              catch(CloneNotSupportedException c){
                   return null;
         public void setColor(Color newColor){
         color = newColor;
         canvas.repaint();
         /** The "primitive" for all resizing/moving/creating operations that
         * affect the rect bounding box. The current implementation just resets
         * the bounds variable and triggers a re-draw of the union of the old &
         * new rectangles. This will redraw the shape in new size and place and
         * also "erase" if bounds are now smaller than before.
         protected void setBounds(Rectangle newBounds){
              Rectangle oldBounds = bounds;
              bounds = newBounds;
              updateCanvas(oldBounds.union(bounds));
         /** The resize operation is called when first creating a rect, as well as
         * when later resizing by dragging one of its knobs. The two parameters
         * are the points that define the new bounding box. The anchor point
         * is the location of the mouse-down event during a creation operation
         * or the opposite corner of the knob being dragged during a resize
         * operation. The end is the current location of the mouse.
         public void resize(Point anchor, Point end){
              Rectangle newRect = new Rectangle(anchor);
              // creates smallest rectange which
              // includes both anchor & end
              newRect.add(end);
              // reset bounds & redraw affected areas
              setBounds(newRect);
              canvas.repaint();
         /** The translate operation is called when moving a shape by dragging in
         * the canvas. The two parameters are the delta-x and delta-y to move
         * by. Note that either or both can be negative. Create a new rectangle
         * from our bounds and translate and then go through the setBounds()
         * primitive to change it.
         public void translate(int dx, int dy){
              Rectangle newRect = new Rectangle(bounds);
              newRect.translate(dx, dy);
              setBounds(newRect);
              canvas.repaint();
         /** Used to change the selected state of the shape which will require
         * updating the affected area of the canvas to add/remove knobs.
         public void setSelected(boolean newState){
              isSelected = newState;
              // need to erase/add knobs
              // including extent of extended bounds
              updateCanvas(bounds, true);
              canvas.repaint();
         /** The updateCanvas() methods are used when the state has changed
         * in such a way that it needs to be refreshed in the canvas to properly
         * reflect the new settings. The shape should take responsibility for
         * messaging the canvas to properly update itself. The appropriate AWT/JFC
         * way to re-draw a component is to send it the repaint() method with the
         * rectangle that needs refreshing. This will cause an update() event to
         * be sent to the component which in turn will call paint(), where the
         * real drawing implementation goes. See the paint() method in
         * DrawingCanvas to see how it is implemented.
         protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
                   System.out.println("canvas2 updated");
              Rectangle toRedraw = new Rectangle(areaOfChange);
              if (enlargeForKnobs)
              toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
              canvas.repaint(toRedraw);
         protected void updateCanvas(Rectangle areaOfChange){
                   System.out.println("canvas updated");
              updateCanvas(areaOfChange, isSelected);
              public Rectangle getBounds(){
                   return bounds;
         /** When the DrawingCanvas needs to determine which shape is under
         * the mouse, it asks the shape to determine if a point is "inside".
         * This method should returns true if the given point is inside the
         * region for this shape. For a rectangle, any point within the
         * bounding box is inside the shape.
         public boolean inside(Point pt){
              return bounds.contains(pt);
         /** When needed, we create the array of knob rectangles on demand. This
         * does mean we create and discard the array and rectangles repeatedly.
         * These are small objects, so perhaps it is not a big deal, but
         * a valid alternative would be to store the array of knobs as an
         * instance variable of the Shape and and update the knobs as the bounds
         * change. This means a little more memory overhead for each Shape
         * (since it is always storing the knobs, even when not being used) and
         * having that redundant data opens up the possibility of bugs from
         * getting out of synch (bounds move but knobs didn't, etc.) but you may
         * find that a more appealing way to go. Either way is fine with us.
         * Note this method provides a nice unified place for one override from
         * a shape subclass to substitute fewer or different knobs.
         protected Rectangle[] getKnobRects(){
                   System.out.println("knobs gotten");
              Rectangle[] knobs = new Rectangle[4];
              knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
              knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              return knobs;
         /** Helper method to determine if a point is within one of the resize
         * corner knobs. If not selected, we have no resize knobs, so it can't
         * have been a click on one. Otherwise, we calculate the knob rects and
         * then check whether the point falls in one of them. The return value
         * is one of NW, NE, SW, SE constants depending on which knob is found,
         * or NONE if the click doesn't fall within any knob.
         protected int getKnobContainingPoint(Point pt){
                   System.out.println("resize knobs");
              // if we aren't selected, the knobs
              // aren't showing and thus there are no knobs to check
              if (!isSelected) return NONE;
              Rectangle[] knobs = getKnobRects();
              for (int i = 0; i < knobs.length; i++)
              if (knobs[i].contains(pt))
                   return i;
              return NONE;
         /** Method used by DrawingCanvas to determine if a mouse click is starting
         * a resize event. In order for it to be a resize, the click must have
         * been within one of the knob rects (checked by the helper method
         * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
         * opposite this corner that will remain fixed as the user drags the
         * resizing knob of the other corner around. During the drag actions of a
         * resize, that fixed anchor point and the current mouse point will be
         * passed to the resize method, which will reset the bounds in response
         * to the movement. If the mouseLocation wasn't a click in a knob and
         * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
              System.out.println("is it a resize?");
    int whichKnob = getKnobContainingPoint(mouseLocation);
    if (whichKnob == NONE) // no resize knob is at this location
    return null;
    Rectangle[] knobs = getKnobRects();
    whichKnob = Math.abs(whichKnob - (int)(knobs.length / 2));
    return (new Point(knobs[whichKnob].x + knobs[whichKnob].width /2,
    knobs[whichKnob].y + knobs[whichKnob].height/2));
    public abstract void draw(Graphics g, Rectangle regionToDraw);

    line left at the end. How can I correct this?java.awt.Polygon (or Polygon2D)
    Here are a few of my thoughts
    #1 There is a Shape interface in core java already, as well as plenty of very useful shapes (Rectangle, Ellipse2D, Area). Shape has some really nice features like contains(...) and intersects(...). By creating a separate class for your Shape objects, you ensure that the two will be incompatible.
    #2 As tempting as it is, it is a bad idea to include a Color with a shape. What if you want it to have more than one Color? What if you want the insides of the shape to be filled by an Image? I just created and posted a class on the java forums called Renderable, which combines a java.awt.Shape with a java.awt.Paint.
    #3 Below is my PaintArea class. It "scribbles" on an Image. Maybe this will give you some ideas. To compile it, you will either have to find my MathUtils class (which I've posted here before) or reimplement the distance and angle methods. There is also a reference to WIndowUtilities... find that or remove it and put the PaintArea in a Frame and do setVisible(true)
    You are welcome to use and modify this code, but please don't change the package and please make sure that you add attribution if you submit this in an academic setting.
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import tjacobs.MathUtils;
    import tjacobs.ui.util.WindowUtilities;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         private static final long serialVersionUID = 0;
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              public static final long serialVersionUID = 0;
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              private static final long serialVersionUID = 1L;
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {
                        private static final long serialVersionUID = 1L;};
                   //int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        @SuppressWarnings("unused")
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • Draw an visio shape as an .vdx file and render the same in a IE browser

    I had generated an Visio Diagrams getting input from the excel file and stored it in an local path.
    private void DynamicVisio_Load(object sender, EventArgs e)
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= 'c:\\Test\\FullData3.xls';Extended Properties='Excel 8.0;HDR=Yes;'";
                string sQuery = "select * from [Customer1_Server$] order by Name";
                DataSet objExcelDS = new DataSet();
                OleDbDataAdapter objDA = new OleDbDataAdapter(sQuery, strConn);
                objDA.Fill(objExcelDS);
                double dblX1 = 0.5d;
                double dblY1 = 10.3d;
                double dblX2 = 2.258d;
                double dblY2 = 6.8d;
                String sText = "";
                String sFilePath = "";
                String sDisk = "";
                String[] sArray;
                String[] separators = { "," };
                String sPicturePath = "C:\\Test\\test.png";
                String sIPRangeValue = "";
                Visio.Application objVApp = new Microsoft.Office.Interop.Visio.Application();
                objVApp.Documents.Add(@"C:\Test\CustomTemplate\ServerTemplate.vsd");// add a document
                for (int i = 0; i < objExcelDS.Tables[0].Rows.Count; i++)
                    Visio.Page objVAPage = objVApp.ActiveDocument.Pages.Add();
                    objVApp.Documents.Add(@"C:\Test\CustomShapes\MyShapes.vss");// add a document
                    Visio.Document objVADoc = objVApp.ActiveDocument;// set the working  document to our new document
                    Visio.Masters objVMasters = objVADoc.Masters;
                    Visio.Master objVMaster = objVMasters.get_ItemU("CustomTab");
                    Visio.Shape objTabShape = objVAPage.Drop(objVMaster, 8.24d, 5.54d);
                    objTabShape.Text = objExcelDS.Tables[0].Rows[0]["VLAN"].ToString(); ;
                    //set the Shape Width
                    objTabShape.get_CellsSRC(
                            (short)Microsoft.Office.Interop.Visio.VisSectionIndices.
                            visSectionObject,
                            (short)Microsoft.Office.Interop.Visio.VisRowIndices.
                            visRowXFormIn,
                            (short)Microsoft.Office.Interop.Visio.VisCellIndices.
                            visXFormWidth).ResultIU = 16.0;
                    //set the shape height
                    objTabShape.get_CellsSRC(
                       (short)Microsoft.Office.Interop.Visio.VisSectionIndices.
                       visSectionObject,
                       (short)Microsoft.Office.Interop.Visio.VisRowIndices.
                       visRowXFormIn,
                       (short)Microsoft.Office.Interop.Visio.VisCellIndices.
                       visXFormHeight).ResultIU = 10.6;
                    Visio.Shape objOuterBox = objVAPage.DrawRectangle(dblX1, dblY1, dblX2, dblY2); // Outer Rectange
                    sFilePath = "C:\\Temp\\ServerTemplate"+i.ToString()+".vsd";
                    objVApp.ActiveDocument.SaveAsEx(@sFilePath, (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visSaveAsWS);
    but I need to generate the same visio diagram over the web application using the Response.ContentType. ie.
    context.Response.ContentType = "application/vdx.visio";
    context.Response.AddHeader("content-disposition", String.Format("attachment;filename=\"{0}.vdx\"", fileName));
    Pls give me an idea about it along with any example if possible.
    Thank you.

    Hi,
    This Visio forum is for general questions. Since your issue is related to developing, I advise you to post this issue on Office for Developer forum.
    https://social.msdn.microsoft.com/Forums/office/en-US/home?category=officedev
    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners
    who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.
    Best regards,
    Greta Ge
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • Help, experiencing minor bugs in program

    this is supposed to use rectangles and you should be able to load and save and they have colors and do a few more things with them, the loading is where it doesn't work.
    *-------------------------------------------------------------- 80 columns ---|
    * This is the main class for the application. It is built along the same
    * lines as the Editor class of project 1. It has a constructor, two instance
    * methods, and a static main()  that kicks the whole thing off.
    * The two instance methods are a menu creation method, and a menuItems
    * initialisation method.  The constructor instantiates the window
    * and sets up its internals by creating and installing the drawing canvas,
    * toolbar, and menus. All of the code works correctly as is and should
    * require no changes.
    * @version      1.1 15/04/01
    * @author       Julie Zelenski
    * @author       Restructured by Ian A. Mason
    * @see       javax.swing.JFrame
    * @see       javax.swing.JMenuBar
    * @see       javax.swing.JMenuItem
    * @see       javax.swing.JMenu
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JavaDraw extends JFrame {
        final Toolbar toolbar = new Toolbar();
        final DrawingCanvas canvas = new DrawingCanvas(toolbar, 350, 350);
        final int menuMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
        final JMenuBar mb = new JMenuBar();
        final String[]
             fileMenuItems = {"Clear all", "Load file", "Save to file", "Quit"};
        final int[] fileKeyCodes = {KeyEvent.VK_N, KeyEvent.VK_O, KeyEvent.VK_S, KeyEvent.VK_Q};
        final ActionListener[] fileActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.clearAll();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.loadFile();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.saveToFile();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(0);}}
        final String[] editMenuItems = {"Cut", "Copy", "Paste", "Delete"};
        final int[] editKeyCodes = {KeyEvent.VK_X, KeyEvent.VK_C, KeyEvent.VK_V, KeyEvent.VK_BACK_SPACE};
        final int[] editMenuMasks = {menuMask, menuMask, menuMask, 0};
        final ActionListener[] editActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.cut();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.copy();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.paste();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.delete();}}
        final String[] layeringMenuItems = {"Bring to front", "Send to back"};
        final int[]    layeringKeyCodes = {KeyEvent.VK_F, KeyEvent.VK_B};
        final ActionListener[] layeringActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.bringToFront();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.sendToBack();}}
        private JavaDraw(){
         super("JavaDraw!");
         toolbar.setCanvas(canvas);
         getContentPane().add(toolbar, BorderLayout.SOUTH);
         getContentPane().add(canvas, BorderLayout.CENTER);
         createMenus();
         setJMenuBar(mb);
         setLocation(100, 20);
         pack();
         setVisible(true);
        static public void main(String[] args){
         JavaDraw javaDraw = new JavaDraw();
        private void initMenus(JMenu m,
                      String  miLabel,
                      int keyCode,
                      int menuMask,
                      ActionListener al){
         JMenuItem mi = new JMenuItem(miLabel);
         m.add(mi);
         mi.addActionListener(al);
         mi.setAccelerator(KeyStroke.getKeyStroke(keyCode, menuMask));
        private void createMenus(){
         JMenu m;
         m = new JMenu("File");
         for(int i = 0; i < fileMenuItems.length; i++)
             initMenus(m,
                    fileMenuItems,
              fileKeyCodes[i],
              menuMask,
              fileActionListeners[i]);
         mb.add(m);
         m = new JMenu("Edit");
         for(int i = 0; i < editMenuItems.length; i++)
         initMenus(m,
              editMenuItems[i],
              editKeyCodes[i],
              editMenuMasks[i],
              editActionListeners[i]);
         mb.add(m);
         m = new JMenu("Layering");
         for(int i = 0; i < layeringMenuItems.length; i++)
         initMenus(m,
              layeringMenuItems[i],
              layeringKeyCodes[i],
              menuMask,
              layeringActionListeners[i]);
         mb.add(m);
    *-------------------------------------------------------------- 80 columns ---|
    * The DrawingCanvas class a small extension of JComponent
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    * @see javax.swing.JComponent
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    public class DrawingCanvas extends JComponent{
    static final int DRAG_NONE = 0;
    static final int DRAG_CREATE = 1;
    static final int DRAG_RESIZE = 2;
    static final int DRAG_MOVE = 3;
    // list of all shapes on canvas
    protected Vector allShapes;          
    // currently selected shape (can be null at times)
    protected Rect selectedShape;
    // reference to toolbar to message for tool&color settings
    protected Toolbar toolbar;
    protected Rect clipboard=null;          
    /* These are the unimplemented menu commands. The menus are already
    * set up to send the correct messages to the canvas, but the
    * method bodies themselves are currently completely empty. It will
    * be your job to fill them in!
    public void cut() {
         copy();
         delete();
    public void copy() {
         int x=(int)selectedShape.getBounds().getX();
         int y=(int)selectedShape.getBounds().getY();
         Point p=new Point(x,y);
         clipboard=new Rect(p,this);
         clipboard.setBounds(selectedShape.getBounds());
    public void paste() {
         if(clipboard==null)
              return;
         allShapes.add(clipboard);
         setSelectedShape(clipboard);
         copy();
         this.repaint();
    public void delete() {
         if(selectedShape==null)
              return;
         else{
         int num=allShapes.indexOf(selectedShape);
         allShapes.remove(num);
         selectedShape=null;
         this.repaint();
    public void clearAll() {
         allShapes.removeAllElements();
         this.repaint();
    public void loadFile() {
         Load load=new Load(this);
         load.setSize(250,200);
         load.validate();
         load.setVisible(true);
    public void done(Vector vect){
         allShapes.removeAllElements();
         for(int i=0;i<vect.size();i++){
              allShapes.add(vect.elementAt(i));
         this.repaint();
    public void saveToFile() {
         Save save=new Save(allShapes);
         save.setSize(250,200);
         save.validate();
         save.setVisible(true);
    public void bringToFront() {
         if(selectedShape==null)
              return;
         int size=allShapes.size();
         int index=allShapes.indexOf(selectedShape);
         for(int i=index+1;i<=size-1;i++){
              allShapes.set(i-1,allShapes.elementAt(i));
         allShapes.set(size-1,selectedShape);
         this.repaint();
    public void sendToBack() {
         if(selectedShape==null)
              return;
         int index=allShapes.indexOf(selectedShape);
         for(int i=index-1;i>=0;i--){
              allShapes.remove(allShapes.elementAt(i+1));
              allShapes.add(i+1,allShapes.elementAt(i));
         allShapes.remove(allShapes.elementAt(0));
         allShapes.add(0,selectedShape);
         this.repaint();
    * Constructor for creating a new empty DrawingCanvas. We set up
    * our size and background colors, instantiate an empty vector of shapes,
    * and install a listener for mouse events using our inner class
    * CanvasMouseHandler
    public DrawingCanvas(Toolbar tb, int width, int height){
         setPreferredSize(new Dimension(width, height));
         setBackground(Color.white);
         toolbar = tb;
         allShapes = new Vector();
         selectedShape = null;
         CanvasMouseHandler handler = new CanvasMouseHandler();
         addMouseListener(handler);
         addMouseMotionListener(handler);
    * All components are responsible for drawing themselves in
    * response to repaint() requests. The standard method a component
    * overrides is paint(Graphics g), but for Swing components, the default
    * paint() handler calls paintBorder(), paintComponent() and paintChildren()
    * For a Swing component, you override paintComponent and do your
    * drawing in that method. For the drawing canvas, we want to
    * clear the background, then iterate through our shapes asking each
    * to draw. The Graphics object is clipped to the region to update
    * and we use to that avoid needlessly redrawing shapes outside the
    * update region.
    public void paintComponent(Graphics g){
         Rectangle regionToRedraw = g.getClipBounds();
         g.setColor(getBackground());
         g.fillRect(regionToRedraw.x, regionToRedraw.y,
              regionToRedraw.width, regionToRedraw.height);
         Iterator iter = allShapes.iterator();
         while (iter.hasNext())
         ((Rect)iter.next()).draw(g, regionToRedraw);
    * Changes the currently selected shape. There is at most
    * one shape selected at a time on the canvas. It is possible
    * for the selected shape to be null. Messages the shape to
    * change its selected state which will in turn refresh the
    * shape with the knobs active.
    protected void setSelectedShape(Rect shapeToSelect) {
         // if change in selection
         if (selectedShape != shapeToSelect) {
         // deselect previous selection
         if (selectedShape != null)
              selectedShape.setSelected(false);
         // set selection to new shape
         selectedShape = shapeToSelect;
         if (selectedShape != null) {
              shapeToSelect.setSelected(true);
    * A hit-test routine which finds the topmost shape underneath a
    * given point.We search Vector of shapes in back-to-front order
    * since shapes created later are added to end and drawn last, thus
    * appearing to be "on top" of the earlier ones. When a click comes
    * in, we want to select the top-most shape.
    protected Rect shapeContainingPoint(Point pt){
         for (int i = allShapes.size()-1; i >= 0; i--) {
         Rect r = (Rect)allShapes.elementAt(i);
         if (r.inside(pt)) return r;
         return null;
    * The inner class CanvasMouseHandler is the object that handles the
    * mouse actions (press, drag, release) over the canvas. Since there is
    * a bit of state to drag during the various operations (which shape,
    * where we started from, etc.) it is convenient to encapsulate all that
    * state with this little convenience object and register it as the
    * handler for mouse events on the canvas.
    protected class CanvasMouseHandler
         extends MouseAdapter implements MouseMotionListener {
         Point dragAnchor;          
         // variables using to track state during drag operations
         int dragStatus;
         /** When the mouse is pressed we need to figure out what
         * action to take. If the tool mode is arrow, the click might
         * be a select, move or reisze. If the tool mode is one of the
         * shapes, the click initiates creation of a new shape.
         public void mousePressed(MouseEvent event){
         Rect clicked = null;
         Point curPt = event.getPoint();
         // first, determine if click was on resize knob of selected shape
         if (toolbar.getCurrentTool() == Toolbar.SELECT) {
              if (selectedShape != null &&
              (dragAnchor = selectedShape.getAnchorForResize(curPt))
              != null) {
              // drag will resize this shape
              dragStatus = DRAG_RESIZE;     
              } else if ((clicked = shapeContainingPoint(curPt)) != null) {
              // if not, check if any shape was clicked
              setSelectedShape(clicked);
              // drag will move this shape      
              dragStatus = DRAG_MOVE;
              dragAnchor = curPt;
              } else {     
              // else this was a click in empty area,
              // deselect selected shape,
              setSelectedShape(null);
              // drag does nothing in this case
              dragStatus = DRAG_NONE;
         } else {
              Rect newShape = new Rect(curPt, DrawingCanvas.this);
              // create rect here
              allShapes.add(newShape);
              setSelectedShape(newShape);
              dragStatus = DRAG_CREATE;          
              // drag will create (resize) this shape
              dragAnchor = curPt;
         /** As the mouse is dragged, our listener will receive periodic
         * updates as mouseDragged events. When we get an update position,
         * we update the move/resize event that is in progress.
         public void mouseDragged(MouseEvent event){
         Point curPt = event.getPoint();
         switch (dragStatus) {
         case DRAG_MOVE:
              selectedShape.translate(curPt.x - dragAnchor.x,
                             curPt.y - dragAnchor.y);
              // update for next dragged event
              dragAnchor = curPt;
              break;
         case DRAG_CREATE: case DRAG_RESIZE:
              selectedShape.resize(dragAnchor, curPt);
              break;
         public void mouseMoved(MouseEvent e) {}
    /** A little helper routine that will be useful for the load & save
    * operations. It brings up the standard JFileChooser dialog and
    * allows the user to specify a file to open or save. The return
    * value is the full path to the chosen file or null if no file was
    * selected.
    protected String filenameChosenByUser(boolean forOpen){
         JFileChooser fc = new JFileChooser(System.getProperty("user.dir") +
                             java.io.File.separator + "Documents");
         int result = (forOpen? (fc.showOpenDialog(this)) :
              fc.showSaveDialog(this));
         java.io.File chosenFile = fc.getSelectedFile();
         if (result == JFileChooser.APPROVE_OPTION && chosenFile != null)
         return chosenFile.getPath();
         return null;
         // return null if no file chosen or dialog cancelled
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.io.*;
    class Load extends JFrame implements ActionListener, Serializable{
         Container contentPane;
         JTextField jtf;
         JButton jb;
         Object obj=null;
         Load load;
         Thread thread;
         DrawingCanvas draw;
         public Load(DrawingCanvas dc){
              draw=dc;
              contentPane=getContentPane();
              contentPane.setLayout(new FlowLayout());
              jtf=new JTextField(20);
              jb=new JButton("Load");
              jb.addActionListener(this);
              contentPane.add(jtf);
              contentPane.add(jb);
         public void actionPerformed(ActionEvent e){
              String text=jtf.getText();
              SimpleObjectReader reader=SimpleObjectReader.openFileForReading(text+".shp");
              if(reader==null){
                   System.out.println("Couldn't open file!");
                   return;
              obj=reader.readObject();
              reader.close();
              draw.done((Vector)obj);
              this.setVisible(false);
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Vector;
    import java.io.*;
    class Save extends JFrame implements ActionListener, Serializable{
         Container contentPane;
         JTextField jtf;
         Vector shapes;
         JButton jb;
         public Save(Vector shapeVector){
              shapes=shapeVector;
              contentPane=getContentPane();
              contentPane.setLayout(new FlowLayout());
              jtf=new JTextField(20);
              jb=new JButton("Save");
              jb.addActionListener(this);
              contentPane.add(jtf);
              contentPane.add(jb);
         public void actionPerformed(ActionEvent e){
              String text=jtf.getText();
              SimpleObjectWriter writer=SimpleObjectWriter.openFileForWriting(text+".shp");
              if(writer==null){
                   System.out.println("Couldn't open file!");
                   return;
              writer.writeObject(shapes);
              writer.close();
              this.setVisible(false);
    *-------------------------------------------------------------- 80 columns ---|
    * The RectShape class defines a simple rectangular shape object.
    * It tracks its bounding box, selected state, and the canvas it is being
    * drawn in. It has some basic methods to select, move, and resize the
    * rectangle. It has methods that draw the shape in the selected or unselected
    * states and updates the canvas whenever the state or bounds of the rectangle
    * change. The code that is there works properly, but you will need to extend
    * and change the code to support additional features.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    import java.awt.*;
    import java.io.*;
    public class Rect implements Serializable{     
    protected Rectangle bounds;
    protected boolean isSelected;
    public Color color;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
    /** The constructor that creates a new zero width and height rectangle
    * at the given position in the canvas.
    public Rect(Point start, DrawingCanvas dcanvas){
         canvas = dcanvas;
         bounds = new Rectangle(start);
         color=canvas.toolbar.getCurrentColor();
    /** The "primitive" for all resizing/moving/creating operations that
    * affect the rect bounding box. The current implementation just resets
    * the bounds variable and triggers a re-draw of the union of the old &
    * new rectangles. This will redraw the shape in new size and place and
    * also "erase" if bounds are now smaller than before. It is a good
    * design to have all changes to a critical variable bottleneck through
    * one method so that you can be sure that all the updating that goes
    * with it only needs to be implemented in this one place. If any of your
    * subclasses have additional work to do when the bounds change, this is
    * the method to override. Make sure that any methods that change the
    * bounds call this method instead of directly manipulating the variable.
    protected void setBounds(Rectangle newBounds){
         Rectangle oldBounds = bounds;
         bounds = newBounds;
         updateCanvas(oldBounds.union(bounds));
    /** The resize operation is called when first creating a rect, as well as
    * when later resizing by dragging one of its knobs. The two parameters
    * are the points that define the new bounding box. The anchor point
    * is the location of the mouse-down event during a creation operation
    * or the opposite corner of the knob being dragged during a resize
    * operation. The end is the current location of the mouse. If you
    * create the smallest rectangle which encloses these two points, you
    * will have the new bounding box. Use the setBounds() primitive which
    * is the bottleneck we are using for all geometry changes, it handles
    * updating and redrawing.
    public void resize(Point anchor, Point end){
         Rectangle newRect = new Rectangle(anchor);
         // creates smallest rectange which
         // includes both anchor & end
         newRect.add(end);
         // reset bounds & redraw affected areas
         setBounds(newRect);      
    public Rectangle getBounds(){
         return bounds;
    /** The translate operation is called when moving a shape by dragging in
    * the canvas. The two parameters are the delta-x and delta-y to move
    * by. Note that either or both can be negative. Create a new rectangle
    * from our bounds and translate and then go through the setBounds()
    * primitive to change it.
    public void translate(int dx, int dy){
         Rectangle newRect = new Rectangle(bounds);
         newRect.translate(dx, dy);
         setBounds(newRect);
    /** Used to change the selected state of the shape which will require
    * updating the affected area of the canvas to add/remove knobs.
    public void setSelected(boolean newState){
         isSelected = newState;
         // need to erase/add knobs
         // including extent of extended bounds
         updateCanvas(bounds, true);
    /** The updateCanvas() methods are used when the state has changed
    * in such a way that it needs to be refreshed in the canvas to properly
    * reflect the new settings. The shape should take responsibility for
    * messaging the canvas to properly update itself. The appropriate AWT/JFC
    * way to re-draw a component is to send it the repaint() method with the
    * rectangle that needs refreshing. This will cause an update() event to
    * be sent to the component which in turn will call paint(), where the
    * real drawing implementation goes. See the paint() method in
    * DrawingCanvas to see how it is implemented.
    protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
         Rectangle toRedraw = new Rectangle(areaOfChange);
         if (enlargeForKnobs)
         toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
         canvas.repaint(toRedraw);
    protected void updateCanvas(Rectangle areaOfChange){
         updateCanvas(areaOfChange, isSelected);
    /** When the DrawingCanvas needs a shape to draw itself, it sends a draw
    * message, passing the graphics context and the current region being
    * redrawn. If the shape intersects with that region, it must draw itself
    * doing whatever it takes to properly represent itself in the canvas
    * (colors, location, size, knobs, etc.) by messaging the Graphics object.
    public void draw(Graphics g, Rectangle regionToDraw){
         if (!bounds.intersects(regionToDraw))
         return;
         g.setColor(color);
         g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
         if (isSelected) { // if selected, draw the resizing knobs
         // along the 4 corners
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs[i].x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    /** When the DrawingCanvas needs to determine which shape is under
    * the mouse, it asks the shape to determine if a point is "inside".
    * This method should returns true if the given point is inside the
    * region for this shape. For a rectangle, any point within the
    * bounding box is inside the shape.
    public boolean inside(Point pt){
         return bounds.contains(pt);
    /** When needed, we create the array of knob rectangles on demand. This
    * does mean we create and discard the array and rectangles repeatedly.
    * These are small objects, so perhaps it is not a big deal, but
    * a valid alternative would be to store the array of knobs as an
    * instance variable of the Shape and and update the knobs as the bounds
    * change. This means a little more memory overhead for each Shape
    * (since it is always storing the knobs, even when not being used) and
    * having that redundant data opens up the possibility of bugs from
    * getting out of synch (bounds move but knobs didn't, etc.) but you may
    * find that a more appealing way to go. Either way is fine with us.
    * Note this method provides a nice unified place for one override from
    * a shape subclass to substitute fewer or different knobs.
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[4];
         knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                        bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                        bounds.y + bounds.height - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                        bounds.y + bounds.height - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                        bounds.y - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         return knobs;
    /** Helper method to determine if a point is within one of the resize
    * corner knobs. If not selected, we have no resize knobs, so it can't
    * have been a click on one. Otherwise, we calculate the knob rects and
    * then check whether the point falls in one of them. The return value
    * is one of NW, NE, SW, SE constants depending on which knob is found,
    * or NONE if the click doesn't fall within any knob.
    protected int getKnobContainingPoint(Point pt){
         // if we aren't selected, the knobs
         // aren't showing and thus there are no knobs to check
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    /** Method used by DrawingCanvas to determine if a mouse click is starting
    * a resize event. In order for it to be a resize, the click must have
    * been within one of the knob rects (checked by the helper method
    * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
    * opposite this corner that will remain fixed as the user drags the
    * resizing knob of the other corner around. During the drag actions of a
    * resize, that fixed anchor point and the current mouse point will be
    * passed to the resize method, which will reset the bounds in response
    * to the movement. If the mouseLocation wasn't a click in a knob and
    * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
         int whichKnob = getKnobContainingPoint(mouseLocation);
         // no resize knob is at this location
         if (whichKnob == NONE)
         return null;
         switch (whichKnob) {
         case NW: return new Point(bounds.x + bounds.width,
                        bounds.y + bounds.height);
         case NE: return new Point(bounds.x, bounds.y + bounds.height);
         case SW: return new Point(bounds.x + bounds.width, bounds.y);
         case SE: return new Point(bounds.x, bounds.y);
         return null;
    import java.io.*;
    * SimpleObjectReader is a small class to wrap around the usual ObjectStream
    * to shield you from the exception handling which we haven't yet gotten
    * to in class.
    * <P>It has just three methods of note: one to open a new file for reading,
    * one to read an object from an open file, and one to close the file when done.
    * <P>Any object that you attempt to read must properly implement the Serializable
    * interface. Here is a simple example that shows using the SimpleFileReader to
    * to rehydrate objects from a file and print them:
    * <PRE>
    * SimpleObjectReader reader = SimpleObjectReader.openFileForReading("shapes");
    * if (reader == null) {
    * System.out.println("Couldn't open file!");
    * return;
    * Object obj;
    * while ((obj = reader.readObject()) != null)
    * System.out.println(obj);
    * reader.close();
    * </PRE>
    * <P>You are free to edit or extend this class, but we don't expect that
    * you should need to make any changes.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    public class SimpleObjectReader {
    private ObjectInputStream ois;
    * Opens a new file for reading. The filename can either be a relative
    * path, which will be relative to the working directory of the program
    * when started, or an absolute path. If the file exists and can be
    * opened, a new SimpleObjectReader is returned. If the file cannot be
    * opened (for any reason: wrong name, wrong path, lack of permissions, etc.)
    * null is returned.
    public static SimpleObjectReader openFileForReading(String filename){
         try {
         return new SimpleObjectReader(new ObjectInputStream(new FileInputStream(filename)));
         } catch(IOException e) {     
         return null;
    * Reads a single object from the file and returns it. If there are
    * no more objects in the file (i.e, we have reached the end of file),
    * null is returned null is returned. null is also
    * returned on any I/O error.
    public Object readObject (){
         try {
         return ois.readObject();
         } catch (IOException e) {
         e.printStackTrace();
         return null;
         } catch (ClassNotFoundException e) {
         e.printStackTrace();
         return null;
    * Closes the file when done reading. You should close a reader when
    * you are finished to release the OS resources for use by others.
    public void close (){
         try {
         ois.close();
         catch (IOException e) {}
    * Constructor is private so that only means to create a new reader
    * is through the static method which does error checking.
    private SimpleObjectReader(ObjectInputStream ois){
         this.ois = ois;
    import java.io.*;
    * SimpleObjectWriter is a small class to wrap around the usual
    * ObjectOutputStream to shield you from the exception handling
    * which we haven't yet gotten to in class.
    * <P>It has just three methods of note: one to open a new file for writing,
    * one to write an object to the file, and one to close the
    * the file when done.
    * <P>Here is a simple example that shows using the SimpleObjectWriter
    * to create a new file and write some objects into it:
    * <PRE>
    * SimpleObjectWriter writer =
    * SimpleObjectWriter.openFileForWriting("objects");
    * if (writer == null) {
    * System.out.println("Couldn't open file!");
    * return;
    * writer.writeObject("Here is a string");
    * writer.writeObject("And another one.");
    * writer.writeObject(new Date());
    * writer.close();
    * </PRE>
    * <P>You are free to edit or extend this class, but we don't expect that
    * you should need to make any changes.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    public class SimpleObjectWriter {
    private ObjectOutputStream oos;
    * Opens a new file for writing. The filename can either be a relative
    * path, which will be relative to the working directory of the program
    * when started, or an absolute path. If the file can be created, a
    * new SimpleObjectWriter is returned. If the file already exists, this
    * will overwrite its content

    I'm not reading that either, but to help you for next time:
    - use more than 1 sentence to describe your problem
    - only post the RELEVANT code, or a small test program with the same problem if possible.
    At least you formatted it, I'll give you that.
    Cheers,
    Radish21
    PS. I think in this case, posting another (better worded) thread might be a good idea, because no one is going to read this one. In general though, don't :)

  • Motion Shape Styles missing, but still in the Library?

    Hi All-
    In Motion 5 I am no longer seeing any shape styles listed in the usual location under the "shape" tab, "style" tab, "Shape Style:" drop-down.  The only option I have is "Save Shape Style...".  Note that shape styles in existing projects still display, I just can't select new ones.  This appears to affect all my projects equally.  And this just appeared today -- previously everything's been working fine.
    I can see in /Library/Application Support/Final Cut Studio/Motion/Library/Shape Styles/ that everything is still present in the filesystem, it's just that Motion seems to not be finding them.  Note also that I still have Motion 4 installed and shape styles do still appear there.
    I tried trashing prefs, no dice.  Permissions in the Library are read-only for everyone, and as far as I know that is typical.
    Ideas?
    Thanks.
    Edit:  This is a Motion *5* question, not FCPX -- there was no Motion 5 option in the post UI.

    Thanks.  I'm aware of the utility, but temporarily swapping out Motion prefs is a simple affair of moving two files out of /Library/Application Support.  No dice.  Shape Styles were still gone with blanked out prefs.
    However they did reappear eventually and then disappear again.  Quitting and re-launching the program a few times may or may not have been responsible for the disappearances/reappearances.  I should note that when this happens, the preset list of gradient fills also disappears.

Maybe you are looking for