Resizing a rectangle shape?

In my drawing application the user uses the mouse to drag out a rectangle. When the rectangle is drawn it has four handles on it, so that the user can click on any one of these handles and resize it. I'm having great difficulties getting this to working properly, does anyone know of an open source example I could look at to see how to do this?
I have resizing a Line working perfectly, all I need now is the rectangle functionality.
Here is how I draw the handles on my rectangle:
public void drawHandles(Graphics2D aGraphics2D)
        aGraphics2D.setColor(Color.RED);
        // If the shape is selected then draw the handles
        if(isSelected())
            aGraphics2D.fillRect(getX1() - 2, getY1() - 2, 5, 5);
             aGraphics2D.fillRect(getX2() - 2, getY2() - 2, 5, 5);
             aGraphics2D.fillRect(getX1() - 2, getY2() - 2, 5, 5);
             aGraphics2D.fillRect(getX2() - 2, getY1() - 2, 5, 5);
    }I have also a method that returns which handle has been clicked.
Please help guys, I've spent too long trying to get this to work.
Thanks.

Probably you do custom painting. So do something like this:
class SuperClass extends JPanel implements MouseListener, MouseMotionListener {
private static final int NO_HANDLE_SELECTED = -1;
private static final int POINTS_COUNT = 4;
private Point[] points = new Point[POINTS_COUNT];
private int editedHandle = NO_HANDLE_SELECTED;
SuperClass(Rectangle rect) {
addMouseListener(this);
addMouseMotionListener(this);
points[0] = new Point(rect.x, rect.y);
points[1] = new Point(rect.x + rect.width, rect.y);
points[2] = new Point(rect.x, rect.y + rect.height);
points[3] = new Point(rect.x + rect.width, rect.y + rect.height);
public void paint(Graphics g) {
// Draw the "rectangle"
g.moveto(points[0]);
for (int i = 1; i < POINTS_COUNT; i++) {
g.lineto(points);
g.lineto(points[0]);
drawHandles(g); // This is your handle drawing routine
* A little bit altered
public void drawHandles(Graphics2D g) {
for (int i = 0; i < POINTS_COUNT; i++) {
g.fillRect(points[i].x - 2, points[i].y - 2, 5, 5);
public void mousePressed(MouseEvent m) {
editedHandle = getEditedHandle(m); // Your handle detecting routine.
// This should return 0 if the first point was clicked e.c.t. or NO_HANDLE_SELECTED
// if the user clicks in empty space.
public void mouseDragged(MouseEvent m) {
if (editedHandle != NO_HANDLE_SELECTED) {
points[editedHandle].x = m.getX();
points[editedHandle].y = m.getY();
repaint();
public void mouseReleased(MouseEvent m) {
editedHandle = NO_HANDLE_SELECTED;
1. Warning. This code was composed on the fly on an HTML browser and not in an IDE. It will probably not run. But with little debugging (1-5 mins) I am sure it will work.
2. This "algorithm" is nice because it paints and edits any polygon without holes, not only Rectangles.
3. This component is being based on JPanel as it is the most likely for you to use. You can adapt it to everything e.g. a JButton in order to edit its (Vectorized) icon when you double click over it! That would be fun!

Similar Messages

  • CANNOT RESIZE THE RECTANGLE/ROUNDED RECTANGLE in Ai CC14

    Hi
    I cannot resize my rectangle shape with the selection tool. Cannot see the bounding box around it and when I hover over the corners of the rectangle a curve appears under the arrowhead. I have tried everything but nothing works.
    Help please. Thanks
    (using cc14 and have uninstalled/installed Ai twice)

    naeem,
    I am afraid you have come across the Live Rectangle bug which is limited to the MAC versions starting with 10.7 and 10.8, but not 10.9 (Mavericks), see this thread linked to below.
    https://forums.adobe.com/thread/1595973
    So a switch to Mavericks with a reinstallation might be the way to solve it here and now.
    To get round it in each case, it is possible to Expand the Live Rectangles to get normal old fashioned rectangles, or to Pathfinder>Unite, or to use the Scale Tool.
    A more permanent way round that is to create normal old fashioned rectangles, after running the free script created by Pawel, see this thread with download link:
    https://forums.adobe.com/thread/1587587

  • Since I've updated, I can't resize rectangle shapes.

    Since I've updated, it seems like I can't resize rectangles or rounded edge rectangles any more.  The bounding box isn't even present, only the nodes for rounding the corners.  This only seems to be happening for the rectangle shapes, ellipses and other polygons are unaffected.  Did they change something, and this is a feature, or is it a bug?
    I've tried restarting and all that, this is happening consistently across many files.  Help!

    Object > Shape > Expand Rectangle
    or use the free transform tool
    For the benefits of live shapes see here:
    Illustrator Help | Live Rectangles and Rounded Rectangles

  • Aligning text horizontally inside a rectangle shape?

    I have text on top of a rectangle made with a shape layer. I now want to align the text in the center of the rectangle shape. I select both layers, though the option to align the text sometimes shows and other times does not. When it does show the horizontal option is greyed out. How is this done?
    Thanks.

    With the Move Tool selected and no Selection active it should be no problem, could you please post a screenshot with the pertinent Panels visible?

  • How do I resize a UML shape?

    how do I resize a UML shape?

    Hi,
    Go to Developer tab> Shape Design Group> Protection> Select None.
    Now, we can resize the UML shape.
    Regards,
    George Zhao
    TechNet Community Support

  • How to resize a rectangle with an image?

    Hey,
    I am working on a MacBook, for me this combination would be "CMD" + "ALT" + "SHIFT" to resize the Rectangle AND the Image placed inside. How is this possible with Indesign script? I'm working with Javascript.
    Thanks really much in advance!!
    Best regards

    I found a workaround. This is not the proper solution, but it works for me. Note: "Width" and "Height" are the geometric bounds of the page substracted. x2-x1 = width, y2-y1 = height.
    newX = width/100*5;
    newY = height/100*5;
    newWidth = width/100*95;
    newHeight = height/100*95;
    Then I just added my rectangle like so:
    myRectangle = rectangles.add({geometricBounds:[newY, newX, newHeight, newWidth]});
    myRectangle.place(File(myFile));
    myRectangle.graphics[0].fit(FitOptions.proportionally);
    myRectangle.graphics[0].fit(FitOptions.centerContent);

  • Drawing an arrow between two rectangle shapes

    i am trying to draw an arrow between two rectangle shapes. the arrow will start from the center of one rectangle and end with the arrow tip at the edge of the other rectangle. i actually draw the arrow first, and draw the rectangles last so the effect of where the arrow starts will seem to come from the edge and not the center.
    i have code using some trigonmetry that works for squares, but as soon as the shape becomes a rectangle (i.e. width and height are not the same), the drawing breaks.
    can i detect where a line intersects with a shape through clipping and use that point location to draw my arrow head? if so, how?

    Here's one way to do this using the rule of similar triangles.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Pointers extends JPanel {
        Rectangle r1 = new Rectangle(40,60,100,150);
        Rectangle r2 = new Rectangle(200,250,175,100);
        int barb = 20;
        double phi = Math.toRadians(20);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            g2.draw(r1);
            g2.draw(r2);
            g2.setPaint(Color.red);
            g2.draw(getPath());
        private GeneralPath getPath() {
            double x1 = r1.getCenterX();
            double y1 = r1.getCenterY();
            double x2 = r2.getCenterX();
            double y2 = r2.getCenterY();
            double theta = Math.atan2(y2 - y1, x2 - x1);
            Point2D.Double p1 = getPoint(theta, r1);
            Point2D.Double p2 = getPoint(theta+Math.PI, r2);
            GeneralPath path = new GeneralPath(new Line2D.Float(p1, p2));
            // Add an arrow head at p2.
            double x = p2.x + barb*Math.cos(theta+Math.PI-phi);
            double y = p2.y + barb*Math.sin(theta+Math.PI-phi);
            path.moveTo((float)x, (float)y);
            path.lineTo((float)p2.x, (float)p2.y);
            x = p2.x + barb*Math.cos(theta+Math.PI+phi);
            y = p2.y + barb*Math.sin(theta+Math.PI+phi);
            path.lineTo((float)x, (float)y);
            return path;
        private Point2D.Double getPoint(double theta, Rectangle r) {
            double cx = r.getCenterX();
            double cy = r.getCenterY();
            double w = r.width/2;
            double h = r.height/2;
            double d = Point2D.distance(cx, cy, cx+w, cy+h);
            double x = cx + d*Math.cos(theta);
            double y = cy + d*Math.sin(theta);
            Point2D.Double p = new Point2D.Double();
            int outcode = r.outcode(x, y);
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    p.x = cx - h*((x-cx)/(y-cy));
                    p.y = cy - h;
                    break;
                case Rectangle.OUT_LEFT:
                    p.x = cx - w;
                    p.y = cy - w*((y-cy)/(x-cx));
                    break;
                case Rectangle.OUT_BOTTOM:
                    p.x = cx + h*((x-cx)/(y-cy));
                    p.y = cy + h;
                    break;
                case Rectangle.OUT_RIGHT:
                    p.x = cx + w;
                    p.y = cy + w*((y-cy)/(x-cx));
                    break;
                default:
                    System.out.println("Non-cardinal outcode: " + outcode);
            return p;
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Pointers());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • How to cut of rectangle shape to create bracket in Photoshop?

    I want a layer like this:
    I've drawn the rectangle then I made a selection with the marquee selection tool to delete a part of the rectangle but it deleted whole shape. Can anyone please help me out with this.
    Thanks in advance.

    hungp15938294 wrote:
    Thanks to Trevor.Dennis and @station_two for helping me . I have more a stupid question because I'm not good at Photoshop. Please take a look at image below
    Make your rectangle shape.  If you want it to be perfectly square, hold down the Shift key while you drag.
    Make your two text layers using the centered text alignment option.
    Select the entire canvas — Ctrl a (Cmd a )
    Select the Move tool and then select the rectangle shape and both text layers.  You should see matching ants at the edges of your image.
    Click on the Align horizontal centers icon in the Options bar. The rectangle and text layers will now be centered vertically in the image.
    If you want the box centered width wise, select just the box layer, and make sure you still have the matching ants at the image edges.
    Click on Align vertical centers second icon from the left in the strip above.
    You will need to align the text layers to intersect the horizontal lines manually, but if you hold down the shift key while dragging, they will not move sideways.
    Nearly done.
    You still need those marching ants at the screed edges (Ctrl a).  Go Select > Transform selection You will now see handles on the selection.
    Hold down the Alt (Opt) key, and drag either the central handles on the vertical sides towards the middle of the box. Both sides will move symmetrically.
    When the select is a couple of mm clear of the wider text, click on the tick icon on the Options bar to OK it.
    Make sure just the box layer is selected, and add a Layer mask. This will actually hide the bits you don't want hidden, so last step.
    Invert the layer mask Ctrl i (Cmd i)

  • Rectangle shape and add to controls to it:

    Hi,
    I've a requirement where I need to add rectangle shapes to the application and I should add text, image and button. I checked with Rectangle shape, but it will not allow us to add controls within that. Please let me know how can I do the same.
    Thanks,
    Santosh

    Just add the Rectangle and the TextBlocks and Image to the same Grid:
    <Grid Width="100">
    <Rectangle Width="100" Height="100" Fill="Green"/>
    <Image Source="pic.png" Width="10" Height="10" Margin="20"/>
    <TextBlock Margin="10 5 10 5">text...</TextBlock>
    </Grid>
    The TextBlock will end up on top of the Image that will end up on top of the Rectangle using the above sample markup. Use the Margin property to control the position of the elements.
    Please remember to close your threads by marking helpful as answer and then start a new thread if you have a new question.

  • I can't resize new rectangles with the new Illustrator 2014

    I know from reading other boards that there are related issues with snapping to grid but I'm having an issue only with resizing rectangles when I create them new. We have others in our company using Creative Cloud that have updated and they are not having the same issue I am having.
    Basically when I create any new rectangle, or rounded corner rectangle it is a fixed size and I am not given the handles to resize it. I have to select the object then go to Object > Shape > Expand Rectangle in order to get the corners to grab and reshape or resize. I have checked and unchecked all of the settings that I can see or read about and nothing changes this. It's a real pain to have to go through this with every object I create.
    I have also tried rebooting the software and my computer several times but it's still the same.
    Am I just missing some small setting somewhere?

  • Flex Help - Creating Resizable, Draggable, Rotatable Shapes

    Hello,
    Hopefully some feedback from this forum can guide me into
    creating what I hope to accomplish.
    What I want to do is have the user be able to draw shapes
    onto a canvas/panel. The shaeps are standard squares, rectangles,
    circles, etc. .... This is the easy part.
    Once the shapes are drawn, I would like for the user to be
    able to click on a shape, and have 4 squares show up at each corner
    of the shape. When a user clicks on one of the squares and drags
    the mouse, the object expands in size. Furthermore, I would like to
    provide the functionality so that the user may rotate the shape.
    I have currently completed the user being able to draw
    shapes, as well as drag them anywhere on the application. I have
    used sprites for this. Can someone please guide me on how to
    incorporate the other functionality such as the user being able to
    resize the shape by selecting a tiny square at one of the corners
    of the object. Thanks

    As cxf02 mentioned in a separate thread:
    http://code.google.com/p/flex-object-handles/downloads/list
    http://www.rogue-development.com/objectHandles.html
    Your work is done :)

  • When creating a rectangle shap, how to manually set dimensions

    I am creating a rectangular shape with the tool (U).
    How can I manually set the dimensions (height and width).
    I know I can see the dimensions with the info button in the right side bar, bug I want to edit those values.
    Is this possible?

    You can set the dimensions before using the rectangle tool in the
    tool options bar (fixed size).
    Or you can change the dimensions after, by using the move tool or Edit<Free Transform Path
    and entering the dimensions in pixels (px) in the width and height boxes.
    MTSTUNER

  • Cannot resize images, textboxes, shapes, etc.

    When I try to resize a shape, a photo or a textbox or try to change the mask on an image, I cannot grab the handles of the box (except, just to make things frustrating, occasionally). Tables can be resized.
    Should I dig out the disk and reinstall and then upgrade the program or is there a simpler way to go?
    thanks for any help,

    It's quite possible that crashing corrupted the Pages preferences. There is no need to reinstall & reinstalling doesn't replace the preference file. Go to HD > Users > (your account) > Library > Preferences & delete the com.apple.iwork.pages.plist & then restart Pages & see if the problem is fixed.

  • JS to add url hyperlink to a rectangle shape?

    Hi there,
    Any JS script to add a url hyperlink to a shape object ?
    Thanks a million....

    Hi,
    here's a script that might help you. I made it and tested it only for InDesign CS5.5.
    How to use it: select any object in InDesign then run the script. At first, the script will try to see in the clipboard has valid URL (well, a text startiong with http…) and if so, the clipboard will be take as a good URL for the new created button. If no valid URL in the clipboard, the script will ask for the URL to be entered manually. If the ibject is a text frame, the script will try to take the text from inside the frame as a URL – if not valid, then the dialog pops up.
    // -------------------------------------------- BEGIN SCRIPT ----------------------------------------------
    if (app.selection.length==1) {
    //get the selected object (only one object)
    var xOBJECT = app.selection[0];
    var xPAGE = xOBJECT.parentPage;
    var xBOUNDS = xOBJECT.geometricBounds;
    //create the button
    var xBUTT = xPAGE.buttons.add({geometricBounds:xBOUNDS});
    //add selected object to the normal state
    xBUTT.states.item(0).addItemsToState(xOBJECT);
    //create the gotoURL behavior
    var xGOTOURL = xBUTT.gotoURLBehaviors.add({behaviorEvent:BehaviorEvents.mouseUp});
    //get the clipboard
    var xTEMP = app.documents[0].textFrames.add(); xTEMP.insertionPoints[-1].select(); app.paste(); var xCLIP = xTEMP.parentStory.contents; xTEMP.remove();
    //check the clipboard or text frame's text; if it does not starts with "http" then it's not good and a dialog asking a good URL will popup
    if (xOBJECT.constructor.name!="Rectangle")
        var xURL = xOBJECT.parentStory.contents;
    } else {
        var xURL = xCLIP;
    if (xURL.substring(0, 6)!="http://") {
    // do the dialog here
    var xDIAG = app.dialogs.add();
    with (xDIAG.dialogColumns.add().dialogRows.add()){staticTexts.add({staticLabel:"Enter URL:"}); var xURLTEXT = textEditboxes.add({editContents:xCLIP, minWidth:160});}
    var xRESULT = xDIAG.show({name:"Button creation"});
    if (xRESULT == true){xURL = xURLTEXT.editContents; xDIAG.destroy();} else { xURL="http://"; xDIAG.destroy();}   
    // set the URL to the behavior
    xGOTOURL.url=xURL;
    // -------------------------------------------- END SCRIPT ----------------------------------------------
    Have fun!

  • Drawing Rectangle shape using Labview 8.0

    Is it possible to draw a rectagle shape using Labview 8.0? I found in the HELP content tat it did exist some function related, but when i click on "place to block diagram" it doesnt work. So i susect tat it is for further version of Labview.
    I have an idea of how to draw the rectagle, which is by drawing line from point to point. Since i need to draw multiple of rectangle, so i hope tat there is an easier way to do it.
    Thanks for ur time and help.

    You can have the numbers created, programmatically
    Attachments:
    Example_VI_BD2.png ‏3 KB

Maybe you are looking for

  • How do you save from Photoshop back to iPhoto?

    How do you save your external edits from Photoshop back to iPhoto? Fine, I know how it can be done ONCE : you simply flatten the image and then hit Save, and you see your edited image in iPhoto. But, what if you FIRST want to save the .psd document c

  • How to creat a text file

    hello everybody I need your help guys in some java issue "surprise" how can I create a text file in java I mean I wanna check if the file is there and if its not I create it thanks

  • Need to run Adobe Customization Wizard every time for each new reader update?

    Hi there, This should be a simple question... Do I need to run Adobe Customization Wizard every time on each new incremental reader update, or just once per major revision (e.g. Reader 9, Reader X)?

  • Lost MY home wifi, no one else's - what's going on?

    My 3Gs has lost, and can't find, my home wifi network. I've had LOTS of hassles with the home network lately due to the Airport Express/Extreme firmware upgrades. Now the home network is mostyl OK but the phone is stuck on 3G. I can find neighbors' w

  • Ajust laptop brightness

    Hello everyone, i have this strange issue: i can't ajust my laptop brightness. The display indicates it is reducing/increasing but nothing happens ...