Moving a shape

Hi,
I have a maze and I want to make it possible for a charachter (an image) to run through the maze. Not taking the walls in acount, he may run through walls, i don't mind i'll program that later.
The maze itself is actually a 2D array filled with 1, 0 values. 1 represents a wall, 0 floor. I have the array run through by two for loops to change the 1 values to wallimages and the 0 values to floorimages. Everything from the maze is drawn in my paintComponent(Graphics g) method.
But I think that's not the main point; my main question is how can I make an image and when I press a button or something, the location of the image is changed. I always have to be able to know the current position of the image though.
Greetz Daan

There doesn't exist such a method for an image. The only graphics where such methods exist are shapes like a rectangle or an oval i quess.
EDIT: I could make a method draw and call it every time the image has to be moved. Something like this:
private void draw(int x, int y, Graphics g)
           g.drawImage(heroimg, x*CELLSIZE, y*CELLSIZE,CELLSIZE,CELLSIZE, this);
      }But offcorse this will always let a copy at the orignal place behind so I get a trail. How do i solve this?
Greetz Daan
Message was edited by:
D-a-a-n

Similar Messages

  • Problem in moving Rotated Shape object

    Hi All,
    I want to move the rotated shape object based on the mouse movement
    m able to move the object which is not rotated, but m facing the problem when i move the rotated object its moving position is not correct . I am expecting to maintain both shape objects movement is same, i mean if i did mouse movement to right rotated object moves upwards and normal object moves towards right insted of moving both r moving towards to right.
    Pls help me
    the following code is m using to moving the object
    The one which in red color is not rotated and the one which is in black color has rotated.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import com.clinapps.LDPConstants;
    public class MoveRotatedObj extends JFrame
         public MoveRotatedObj()
              JPanel pane = new Dorairaj();
              add(pane);
         public static void main(String[] args)
              MoveRotatedObj f = new MoveRotatedObj();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(400, 400);
              f.setLocation(200, 200);
              f.setVisible(true);
         static class Dorairaj extends JPanel
              implements
                   MouseListener,
                   MouseMotionListener
              Shape o = null;
              Rectangle2D rect = new Rectangle2D.Double(
                   10, 10, 100, 100);
              Graphics2D g2 = null;
              boolean flag = true;
              int x=10,y=10,x1, y1, x2, y2;
              AffineTransform af = new AffineTransform();
              AffineTransform originalAt = new AffineTransform();
              int origin = 0;
              public Dorairaj()
                   addMouseListener(this);
                   addMouseMotionListener(this);
              protected void paintComponent(Graphics g)
                   super.paintComponent(g);
                   g2 = (Graphics2D) g;
                   g2.draw(new Rectangle2D.Double(0,0,500,500));
                   g2.translate(origin, origin);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                   rect = new Rectangle2D.Double(
                        x, y, 150, 100);
                   g2.setColor(Color.RED);
                   g2.draw(rect);
                   g2.setColor(Color.black);
                   originalAt = g2.getTransform();
                   g2.rotate(Math.toRadians(270), 200, 200);               
                   g2.draw(rect);
                   g2.setTransform(originalAt);
              * Invoked when a mouse button has been pressed on a component.
              public void mousePressed(MouseEvent e)
                   e.translatePoint(-origin, -origin);
                   x1 = e.getX();
                   y1 = e.getY();
              public void mouseDragged(MouseEvent e)
                   x2 = e.getX();
                   y2 = e.getY();
                   x = x + x2 - x1;
                   y = y + y2 - y1;
                   x1 = x2;
                   y1 = y2;
                   repaint();
              public void mouseMoved(MouseEvent e)
              * Invoked when the mouse button has been clicked (pressed and released)
              * on a component.
              public void mouseClicked(MouseEvent e)
                   repaint();
              * Invoked when a mouse button has been released on a component.
              public void mouseReleased(MouseEvent e)
              * Invoked when the mouse enters a component.
              public void mouseEntered(MouseEvent e)
              * Invoked when the mouse exits a component.
              public void mouseExited(MouseEvent e)
    Edited by: DoraiRaj on Sep 16, 2009 12:51 PM
    Edited by: DoraiRaj on Sep 16, 2009 1:00 PM
    Edited by: DoraiRaj on Sep 16, 2009 1:07 PM

    Thanks for replay and suggestion morgalr,
    I mean MoveRotatedObj1 is MoveRotatedObj only jsut m maintaing a copy on my system like MoveRotatedObj1.
    finally i solved my problem like this ,
    Is this correct approach m followinig or not pls let me know .
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import com.clinapps.LDPConstants;
    public class MoveRotatedObj extends JFrame
    public MoveRotatedObj()
      JPanel pane = new Dorairaj();
      add(pane);
    public static void main(String[] args)
      MoveRotatedObj f = new MoveRotatedObj();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setSize(400, 400);
      f.setLocation(200, 200);
      f.setVisible(true);
    static class Dorairaj extends JPanel
      implements
       MouseListener,
       MouseMotionListener
      Shape o = null;
      Rectangle2D rect = new Rectangle2D.Double(
       10, 10, 100, 100);
      Rectangle2D rect1 = new Rectangle2D.Double(
       10, 10, 100, 100);
      Graphics2D g2 = null;
      boolean flag = true;
      double lx, ly;
      int x = 10, y = 10, x1, y1, x2, y2;
      int l = 20, m = 20;
      int angle = 270;
      AffineTransform af = new AffineTransform();
      AffineTransform originalAt = new AffineTransform();
      int origin = 0;
      public Dorairaj()
       addMouseListener(this);
       addMouseMotionListener(this);
      protected void paintComponent(Graphics g)
       super.paintComponent(g);
       g2 = (Graphics2D) g;
       g2.draw(new Rectangle2D.Double(
        0, 0, 500, 500));
       g2.translate(origin, origin);
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
       rect = new Rectangle2D.Double(
        x, y, 150, 100);
       g2.setColor(Color.RED);
       g2.draw(rect);
       rect1 = new Rectangle2D.Double(
        l, m, 150, 100);
       g2.setColor(Color.black);
       originalAt = g2.getTransform();
       g2.rotate(Math.toRadians(angle), 200, 200);
       g2.draw(rect1);
       g2.setTransform(originalAt);
      public void mousePressed(MouseEvent e)
       e.translatePoint(-origin, -origin);
       x1 = e.getX();
       y1 = e.getY();
      public void mouseDragged(MouseEvent e)
       boolean left, right, up, bottm;
       int dx, dy;
       left = right = up = bottm = false;
       x2 = e.getX();
       y2 = e.getY();
       dx = x2 - x1;
       dy = y2 - y1;
       x = x + dx;
       y = y + dy;
       up = dy < 0;
       bottm = dy > 0;
       left = dx < 0;
       right = dx > 0;
       if (left || right)
        // b += dx;
        m += dx;
       if (up || bottm)
        // a -= dy;
        l -= dy;
       x1 = x2;
       y1 = y2;
       repaint();
      public void mouseMoved(MouseEvent e)
      public void mouseClicked(MouseEvent e)
       repaint();
      public void mouseReleased(MouseEvent e)
      public void mouseEntered(MouseEvent e)
      public void mouseExited(MouseEvent e)
    }

  • Unexpected behavior when moving a shape & text

    Any one else run into this on Mac CS6?
    I've selected a shape layer and a text layer at the same time. When I move the shape layer, the text goes in unexpected directions. But when I move the text layer, the objects move as expected. Weird!
    Does CC1 and CC2014 still do this?

    I can replicate your behavior by selecting the text layer and the diamond layer then dragging. That's completely normal because the position parented diamond layer becomes 0,0 when parented and movement of the selected Text layer is based on the recalculated positions. When you get all layers to move together you have selected all 3 ayers. The behavior is completely normal. The only way to prevent this kind of odd movement when selecting two objects, one of which is parented to another, is to work in a square composition. If you can wrap your head around the math you'll figure out why.

  • Moving masks/shapes

    I am trying to have a shape mask (inverted) that highlights one player of a basketball team. I used an inverted shape with a high degree of transparency on the background so the highlighted player is clear within an oval and the rest are slightly grayed out. My problem is that as I keyframe it to move the oval with the player, the mask has a rectangular edge that does not reach all the way to the outside of the frame. If I pull it bigger, the oval becomes bigger too, too big in fact because then other players are inside the oval too. I'm obviously doing something wrong. Any advice? Thanks.
    PowerBookG4 (1 GB RAM)   Mac OS X (10.3.8)   LaCie 160Gb Ext. HD, Sony DCR-VX2100

    try my Region Blur plugin at http://homepage.mac.com/andymees
    you can use it to the same effect (invert on, set blur to zero, add some tint, then just keyframe the center property)
    hope it helps
    Andy

  • Moving 3D Shape

    Hi,
    I need some help in animating a 3D Shape rotating/translating using values entered in JTextField format,
    For example, I want the shape to rotate 60 degrees, I just key in 60 and the shape will be shown rotating 60 degrees.
    Thanks
    th

    Please study my code below. Ignore the parts you don't take interest. Class GeneralContourPanel is no importance to you either. This class cannot run as a standalone app. Just study how we rotate a 3D object. If necessary, you can get in touch with me by this email address: [email protected].
    package petrochina.riped.plot.post3d;
    import com.sun.j3d.utils.behaviors.mouse.MouseRotate;
    import com.sun.j3d.utils.behaviors.mouse.MouseTranslate;
    import com.sun.j3d.utils.behaviors.mouse.MouseZoom;
    import com.sun.j3d.utils.universe.SimpleUniverse;
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.GraphicsConfiguration;
    import javax.media.j3d.Background;
    import javax.media.j3d.BoundingSphere;
    import javax.media.j3d.BranchGroup;
    import javax.media.j3d.Canvas3D;
    import javax.media.j3d.GeometryArray;
    import javax.media.j3d.IndexedLineArray;
    import javax.media.j3d.Shape3D;
    import javax.media.j3d.Transform3D;
    import javax.media.j3d.TransformGroup;
    import javax.vecmath.Color3f;
    import javax.vecmath.Point3d;
    import javax.vecmath.Point3f;
    import javax.vecmath.Vector3d;
    import petrochina.riped.util.Text2DForJ3D;
    * Acts as the base class for any Java3D objects.
    * <p>IMPORTANT NOTICE: The x-y-z axises used in this class is the same with
    * that in Java3D, only the default view is with a rotation.
    * @author Xiao Xiaochun & uanglin Du ([email protected] or [email protected])
    * @version 1.0, 2003/09/29 20:05
    public abstract class J3DPanel extends GeneralContourPanel {   
    /** The root BranchGroup */
    public BranchGroup rootBG = null;
    /** The root of the branch graph */
    public BranchGroup branchGroup = null;
    /** The <code>TransformGroup</code> used to hold . */
    public TransformGroup transformGroup = null;
    /** The <code>Transform3D</code> instance used to resume the visual view. */
    public Transform3D tempRotateTransform = null;
    /** The <code>Transform3D</code> instance used to scale the 3D objects. */
    public Transform3D scaleTransform = null;
    /** The <code>Transform3D</code> instance used in zoom functionality. */
    public Transform3D zoomTransform = null;
    * The <code>Transform3D</code> instance used to rotate the view in x y and z axis
    * clockwiselyorcounter.
    public Transform3D transform3DObject = null;
    /** The MouseTranslate to translate the 3D objects */
    public MouseTranslate myMouseTranslate = null;
    /** The incremental roation counterclockwise angle in radian. */
    private static double rotationIncrement =Math.PI/18.0;
    /** The zoom in count in double. */
    private static double zoomInFactor = 1.02;
    /** The zoom out count in double. */
    private static double zoomOutFactor = 0.98;
    /** The double-typed translate factor. */
    private static double translateFactor = 0.005;
    /** The only Canvas3D instance containing the Java3D objects. */
    private Canvas3D canvas3D = null;
    /** The zox slices indices (row), starting from 1. */
    public int[] zoxSliceIndices = null;
    /** The yoz slices indices (column), starting from 1. */
    public int[] yozSliceIndices = null;
    /** Determines if the 3D view has mesh drawn together, and the default value is true. */
    public boolean withMesh = true;
    /** Determines if the 3D view has well drawn together, and the default value is true. */
    public boolean withWell = true;
    /** Determines if the 3D view has well names drawn together, and the default value is true. */
    public boolean withWellName = true;
    /** Determines if the 3D view has the surrounding frame drawn together, and the default value is false. */
    public boolean withFrame = false;
    /** Determines if the 3D view has a 3D coordinate system drawn together, and the default value is false. */
    public boolean with3DCoord = false;
    * Constructs with a <code>title</code> and <code>workspaceDir</code>.
    * @param contourInfo the information of the contour
    * @param workspaceDir the workspace directory
    public J3DPanel(String contourInfo, String workspaceDir) {          
         super(contourInfo, workspaceDir);
    this.rootBG = new BranchGroup();
    this.rootBG.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
    this.rootBG.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
    this.rootBG.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
    //Creates & adds the Java3D canvas3D to this internal frame's content pane.
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
    this.canvas3D = new Canvas3D(config);
    // SimpleUniverse is a Convenience Utility class
    SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
         // This will move the ViewPlatform back a bit so the
         // objects in the scene can be viewed.
    simpleU.getViewingPlatform().setNominalViewingTransform();
    simpleU.addBranchGraph(this.rootBG);
    * Performs the scene graph initialization. This method is called by subclasses
    * to implement the specific 3D graph plotting.
    public void initialize() {     
         branchGroup = new BranchGroup();
    branchGroup.setCapability(BranchGroup.ALLOW_DETACH);
         transformGroup = new TransformGroup();
         tempRotateTransform =new Transform3D();
         scaleTransform = new Transform3D();
         transform3DObject = new Transform3D();
    zoomTransform = new Transform3D();
         transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
         transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
         branchGroup.addChild(transformGroup);
         //Adds the 3D axis
    if(this.withFrame){
    transformGroup.addChild(create3DAxis());
    } else {
    SimpleAxis sa = new SimpleAxis(0.08f);
    TransformGroup tg = sa.create3DAxis(-0.7, 0.7, 0.0);
    transformGroup.addChild(tg);
    //This is the magic to integrate Java3D with Swing.
         this.setLayout(new BorderLayout());
         this.add(canvas3D, BorderLayout.CENTER);
    //The bounding sphere
    Point3d p3d = new Point3d(0.0, 0.0, 0.0);
    BoundingSphere bs = new BoundingSphere(p3d, 10000);     
         //Adds the mouse translate, rotate & zoom behaviors
         myMouseTranslate = new MouseTranslate();
         myMouseTranslate.setTransformGroup(transformGroup);
         myMouseTranslate.setFactor(translateFactor);
    myMouseTranslate.setSchedulingBounds(bs);
         branchGroup.addChild(myMouseTranslate);
    MouseRotate myMouseRotate = new MouseRotate();
    myMouseRotate.setTransformGroup(transformGroup);
    myMouseRotate.setSchedulingBounds(bs);
    branchGroup.addChild(myMouseRotate);
    MouseTranslate myMouseTranslate = new MouseTranslate();
    myMouseTranslate.setTransformGroup(transformGroup);
    myMouseTranslate.setSchedulingBounds(bs);
    branchGroup.addChild(myMouseTranslate);
    MouseZoom myMouseZoom = new MouseZoom();
    myMouseZoom.setTransformGroup(transformGroup);
    myMouseZoom.setSchedulingBounds(bs);
    branchGroup.addChild(myMouseZoom);
         //Set the window size
         this.setSize(300,300);
         //Set the window's location.
         this.setLocation( 0, 0);                
         this.setVisible(true);
         //default background(white) setting, DGL, 01/25/2002
         Background backg = new Background(1.0f, 1.0f, 1.0f);
    backg.setApplicationBounds(bs);
         branchGroup.addChild(backg);     
         //Uses an abstract method as the entry to add specific 3D objects
    add3DShapes();
         // Let Java 3D perform optimizations on this scene graph.
    branchGroup.compile();
    //simpleU.addBranchGraph(branchGroup);
    this.rootBG.addChild(branchGroup);
    * This abstract method works as the entry for subclasses to addthe Java3D shapes.
    * This is done by adding the 3D objects, usually <code>Shape3D</code> objects
    * to the <code>transformGroup</code> node. A sample is as following:<p>
    * <code>transformGroup.addChild(new ColorCube(0.4));<code>
    * <br>or<p>
    * <code>transformGroup.addChild(new Shape3D(<code>NodeComponent</code> object));<code>
    public abstract void add3DShapes();
    /** Rotates along the view axis about x counterclockwisely */
    public void rotateAlongXCCW() {
         tempRotateTransform.rotX(rotationIncrement);
         transformGroup.getTransform(transform3DObject);
         transform3DObject.mul(tempRotateTransform);
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    /** Rotates along the view axis about y counterclockwisely */
    public void rotateAlongYCCW() { 
         tempRotateTransform.rotY(rotationIncrement);
         transformGroup.getTransform(transform3DObject);
         transform3DObject.mul(tempRotateTransform);
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    /** Rotates along the view axis about z counterclockwisely */
    public void rotateAlongZCCW() { 
         tempRotateTransform.rotZ(rotationIncrement);
         transformGroup.getTransform(transform3DObject);
         transform3DObject.mul(tempRotateTransform);
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    /** Rotates along the view axis about x clockwisely */
    public void rotateAlongXCW() { 
         tempRotateTransform.rotX(-rotationIncrement);
         transformGroup.getTransform(transform3DObject);
         transform3DObject.mul(tempRotateTransform);
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    /** Rotates along the view axis about y clockwisely */
    public void rotateAlongYCW() { 
         tempRotateTransform.rotY(-rotationIncrement);
         transformGroup.getTransform(transform3DObject);
         transform3DObject.mul(tempRotateTransform);
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    /** Rotates along the view axis about z clockwisely */
    public void rotateAlongZCW() { 
         tempRotateTransform.rotZ(-rotationIncrement);
         transformGroup.getTransform(transform3DObject);
         transform3DObject.mul(tempRotateTransform);
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    * Rotates the Java3D objects to the conventional view in
    * reservoir enginering: x axis extends upwardly, y right, and z inwardly.
    public void setPlanform() {
         Transform3D planformTransform = new Transform3D();
         planformTransform.rotX(Math.PI);
         transformGroup.getTransform(transform3DObject);
         transform3DObject = planformTransform;
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;     
    * Rotates the Java3D objects to the conventional view in
    * reservoir enginering: x axis extends downwardly, y right, and z outwardly.
    public void setFundusView() {
         Transform3D fundusTransform = new Transform3D();
         fundusTransform.rotX(2.0*Math.PI);
         transformGroup.getTransform(transform3DObject);
         transform3DObject = fundusTransform;
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;     
    * Rotates the Java3D objects to the conventional view in
    * reservoir enginering: y axis extends inwardly, x left, and z downwardly.
    public void setLeftView() {
         Transform3D leftTransformX = new Transform3D();
         Transform3D leftTransformY = new Transform3D();
         leftTransformX.rotX(Math.PI/2.0);
         leftTransformY.rotY(Math.PI/2.0);
         leftTransformY.mul(leftTransformX);
         transformGroup.getTransform(transform3DObject);
         transform3DObject = leftTransformY;
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;     
    * Rotates the Java3D objects to the conventional view in
    * reservoir enginering: x axis right, y outwardly, and z downwardly.
    public void setRightView() {
         Transform3D rightTransformX = new Transform3D();
         Transform3D rightTransformY = new Transform3D();     
         rightTransformX.rotX(Math.PI/2.0);
         rightTransformY.rotY(1.5*Math.PI);
         rightTransformY.mul(rightTransformX);
         transformGroup.getTransform(transform3DObject);
         transform3DObject = rightTransformY;
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;     
    /** Sets the default view which lets the user overlook the most parts of the 3D graph. */
    public void setDefaultView(){
    this.setFrontView();
    this.rotateAlongXCCW(); //twice
    this.rotateAlongXCCW();
    this.rotateAlongZCW();
    * Rotates the Java3D objects to the conventional view in
    * reservoir enginering: x axis extends inwardly, y right, and z downwardly.
    public void setFrontView() {
         Transform3D frontTransform = new Transform3D();     
         frontTransform.rotX(Math.PI/2.0);
         transformGroup.getTransform(transform3DObject);
         transform3DObject = frontTransform;
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;     
    * Rotates the Java3D objects to the conventional view in
    * reservoir enginering: x axis extends outwardly, y left, and z downwardly.
    public void setBackView() {
         Transform3D backTransformX = new Transform3D();     
         Transform3D backTransformY = new Transform3D();     
         backTransformX.rotX(Math.PI/2.0);
         backTransformY.rotY(Math.PI);
         backTransformY.mul(backTransformX);     
         transformGroup.getTransform(transform3DObject);
         transform3DObject = backTransformY;
         transformGroup.setTransform(transform3DObject);
         zoomTransform = transform3DObject;
    /** Sets the J3D object's zoom in . */
    public void setZoomIn() {
         tempRotateTransform.set(zoomInFactor);
         transformGroup.getTransform(scaleTransform);
         scaleTransform.mul(tempRotateTransform);
         transformGroup.setTransform(scaleTransform);
    /** Sets the J3D object's zoom out. */
    public void setZoomOut() {
         tempRotateTransform.set(zoomOutFactor);
         transformGroup.getTransform(scaleTransform);
         scaleTransform.mul(tempRotateTransform);
         transformGroup.setTransform(scaleTransform);
    /** Sets the J3D object's zoom. */
    public void setZoom() {
         transformGroup.setTransform(zoomTransform);
    /** Removes the main graph from branchGroup. */
    public void removeBranchGroup(){
    try {
    this.branchGroup.detach();
    } catch(Throwable ex) {
    super.exceptionHandler(ex);
    }

  • Moving a shape randomly through a JFrame

    I'm trying to make a rectangle move to an arbitrary position when the mouse is clicked. I can't get the mouseClicked method to call the fillRect one. Does anyone know what I should do?
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.Random;
    import javax.swing.JApplet;
    import javax.swing.JFrame;
    public class ex4 extends JFrame implements MouseListener {
    Random numGen = new Random();
             Color getRandomColor() {
                return new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
    Random generator = new Random();
    int randomIndex = generator.nextInt( 400 );
         private String message = new String ("");
         private Color myColor = Color.WHITE;
         public ex4() {
              setSize(400,400);
              setTitle("ex4");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              addMouseListener(this);
              setVisible(true);
              this.setBackground(Color.WHITE);
         public void paint(Graphics g) {
              super.paint(g);
              int x = generator.nextInt();
              int y = generator.nextInt();
                 g.setColor(getRandomColor());
              g.fillRect( x, y, x/2, y/2);
         public void mouseClicked(MouseEvent arg0) {
         public void mouseEntered(MouseEvent arg0) {
         public void mouseExited(MouseEvent arg0) {
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
          * @param args
         public static void main(String[] args) {
              new ex4();
         public void setMyColor(Color myColor) {
              this.myColor = myColor;
         public Color getMyColor() {
              return myColor;
         

    scheng12 wrote:
    this is an entirely different code than my other thread.and yet yet you're still committing the same error of trying to draw directly to the JFrame and adding a MouseListener directly to the JFrame.

  • Selecting shape after it was Send-to-Back

    I cannot select any object after it was Send-to-Back.

    I have experimented with a blank page and placed several different shapes on it. I moved one shape to the back using Send to Back and deselected it.
    After deselection of the shape Send to Back this shape is not selectable again. There is no way to selected it and move it. The only remedy is to delete the page.

  • Editing Shapes in an External Editor?

    Edit Path in Keynote is nice, but there are times when it would really be handy to be edit Keynote shapes in an external editor. I can Copy/Paste a shape from Keynote into an external editor (like VectorDesigner) and edit it but whenever I copy a shape from an external editor (VectorDesigner, Intaglio, etc.) and paste it into Keynote, it always gets pasted as a PDF and I can't edit it further within Keynote.
    Does anyone know a way of moving editable shapes from Keynote to another program and back again? I've tried saving as SVG in the external editor and doing an Insert Choose... in Keynote but it seems that Keynote always interprets things as non-editable PDFs.

    Waaay back in the day when I realized how close SVG was to Keynote's shapes, I went around to all the Mac-only devs and pitched the idea. The only one that bit was the EazyDraw developers. A few emails later and we had a working solution (they even changed a feature to the app to accommodate one shape being cut out of the other). As of now, that is still the ONLY solution for exporting a shape document out of a drawing app directly to a Keynote file.
    I'd thought that once that threshold was crossed, everyone else would be wanting to at least match that feat, but no go... I even talked to the companies in person at Macworld and still no interest. So, hat's off to Dekorra Graphics!

  • Find and Replace Shape

    I'm a cartographer and converted from FreeHand to Illustrator several years ago. One thing I seriously need is the ability to take a shape and convert it to another shape. i.e I have several circles at a certain size and color and I need to change all of those symbols to a diamond of a different size and color. FreeHand had a Find and Replace Graphic option where I could copy in the original graphic and copy in what I wanted the graphic to change to. Then I would go and select all the original graphics, hit replace and it would change everything WITHOUT moving the shapes as a whole.
    This also relates to the ability to scale of a bunch of circles in one fell swoop without having to go to each individual cirlce and scaling each.
    Does Illustrator have the ability to do either of the things I just described? I have been searching the forums and can't seem to find an answer. This would help me (and I would bet thousands of other cartographers who have to export data out of ArcMap for stylization!)
    Thank you!

    Aha, I guess using the right word in help would be good! I've tried shape, vector, graphic, etc., but not symbol! Thank you to you all. I will try this.
    One other question...when I bring documents in from FreeHand, all of the text boxes are permanently sized. Is it possible to convert all text boxes to auto expand at one time?
    Much thanks!

  • Reconnecting templates, styles, shapes, etc.

    Hi, I'm trying to figure out how to relink DVDSP templates, styles, shapes, etc. as I've moved them to a new location on an external drive. I've done this with Soundtrack Pro and Livetype with no problems, but for some reason I can't figure out DVDSP4.
    I did try clicking Import in the Shapes tab, but it moved the shapes into the custom tab area, which isn't right. And also the templates tab doesn't have an import button, so i figure that isn't the correct method.
    Can I do this? Or do I have to leave the files on the same drive as the application?

    Thank you Drew! Looking for Palette Elements under Destinations was far from intuitive and I came here (rather than open the Manual where it is all explained).
    I hope the OP is happy now.

  • Pages 5 - "TEXT" in background - Can't remove?

    I bought a Pages template collection from the app store (Nick Maskill - Document Pro for Pages). I am using one brochure template (architecture).
    There are several "blocks" in the brochure, each either blue or white. A headline and paragraph text appears in each.
    Behind two of the blocks of text, there is text that simply says: Text ....Looks like Times Roman -- which is NOT what the template is using.
    I've moved the headline and paragraph text block out of the way, but I still can't click on this background TEXT to get rid of it.
    I've tried moving a shape on top of it to cover it up, but when I drag a square to cover it -- the TEXT just slides out of the way.
    I try to right-click on it, but there are only 3 options, to copy, paste or delete. None have any effect.
    Any ideas how I can get rid of this TEXT???
    I'm using the LATEST version of Pages (2013) and this template says it is compatible.

    Brad,
    Your Shape has Wrap set to Automatic, I would imagine. That would explain text running away from it.
    A better approach would be to eliminate the unused Text Box. Since you have trouble selecting it, I'd guess that it is set to be a Section Master. If so, there are two ways to select it. 1. Go to Arrange > Section Masters and Make Master Objects Selectable. Then click on the word Text.  2. position your pointing device cursor in one of the upper corners of the document window, just inside what would be the corner of the page. Then hold down the Command Key as you drag across the page until the text box is encountered.
    When selected, the sizing handles of a Section Master object are yellow-filled circles. Once Selected, hit Delete.
    Jerry

  • 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;
    }

  • 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 :)

  • Can you stop an item in a particular spot during the final motion?

    I moved a shape horizontally to a particular spot and it stops there when you click on the menu item / anchor point. But if you scroll beyond that point, or click the next anchor point, the shape continues off the page. It would be great if I could have it stop horizontally and lock with the page scroll so it continues up the browser without running off the page. Even better if I could make the opacity 0 at the pixel beyond the anchor point so it would simply disappear at that spot when scrolling / clicking beyond that point. Possible?

    Thanks Heike...  I was hoping that there might be some way I couldn't think of & still only use 1 template here.  But as you suggested, I can put the CHANGE_TEMPLATE command in our existing 0QUERY_TEMPLATE copy and then make a new copy for it to branch to -- making sure that my new dataprovider gets filled in with its appropriate query/cube.  This at least minimizes impact by not having to change everything we have that references our 0QUERY_TEMPLATE copy through menus, JavaScript, favorites, etc.
    I am familiar with the 'flicker' effect when we have used the CHANGE_TEMPLATE in the past (bringing up 'Info' for a query in a new window while maintaining the state of the report in the existing window).  In this case, since the report is being created in a new window, it really isn't noticeable at all unless you watch the browser status or the URL command.  Thanks for the information...
    Jody

  • Where are the auto recovery files stored for Visio 2010?

    I have auto recovery set for every 5 minutes.  I have been working on a file that has been saved several times a day.  Today when just moving a shape Viso 2010 crashed after I had been working on the file for over 2 hours.  Auto recovery popped
    up every 5 minutes indicating it was saving the file.  After the crash the ony file I could find was the file as it was when I first opened it this AM.  None of the work done today was saved. 
    Did auto recovery completely fail?  Where can I look for the auto recovery file? 
    I have not done a reboot because I am afraid that if the file exits it will be gone for sure if I reboot.  Any suggestions are welcome.
    There must be a temp file or something that I can look for but not sure what the extension would be or the location.
    Hopefully someone here can help.
    thanks,
    greg
    Greg J Wilson

    How do I know? You state the the auto-save file extension is .vxd - that's the Visio document XML format.
    You can change this in File -> Options -> Save
    As for the crashes, are there any messages when a crash occurs?
    Check that the video drivers you have are the latest, try a different screen resolution to see if that changes anything and turn off or change any screen accelerators.
    -- Paul Herber, Sandrila Ltd. http://www.sandrila.co.uk/ Engineering and software shapes for Visio.
    My mistake - the file format is .vsd - standard visio format
    Here is the info from the event viewer for the specific crash that caused me temporary pain.
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
    <System>
    <Provider
    Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated
    SystemTime="2011-07-25T17:15:25.000000000Z" />
    <EventRecordID>83552</EventRecordID>
    <Channel>Application</Channel>
    <Computer>gw-Tosh_laptop</Computer>
    <Security
    />
    </System>
    <EventData>
    <Data>VISIO.EXE</Data>
    <Data>14.0.6022.1000</Data>
    <Data>4d6eacd6</Data>
    <Data>unknown</Data>
    <Data>0.0.0.0</Data>
    <Data>00000000</Data>
    <Data>c0000005</Data>
    <Data>8469f91f</Data>
    <Data>1668</Data>
    <Data>01cc4ae02611b81c</Data>
    <Data>C:\Program
    Files\Microsoft Office\Office14\VISIO.EXE</Data>
    <Data>unknown</Data>
    <Data>af70a4ff-b6e1-11e0-82fc-001e33913568</Data>
    </EventData>
    </Event>
    Greg J Wilson

Maybe you are looking for