Drawing a rectangle using a mouse

Need a simple application that demostrates the use of the mouse on an application window. All that I require is that a user can draw a rectangle by dragging the mouse on the application window. The upper left coordinate should be the location where the user presses the mouse button and the lower right should be where the user releases the mouse button. Should also display the area of the rectangle in a JLabel in the SOUTH region of a BorderLayout.
Thanks

How is this:
import java.awt.event.*;  
import java.awt.*;
import javax.swing.*;
public class DrawR extends JFrame
     JLabel label = new JLabel();
public DrawR()
     addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
          {     dispose();
               System.exit(0);
     setBounds(50,50,450,400);
     getContentPane().setLayout(new BorderLayout());
     Draw draw = new Draw();     
     getContentPane().add("Center",draw);
     getContentPane().add("South",label);
    setVisible(true);     
public class Draw extends JPanel
     Rectangle r = null;
public Draw()
     addMouseListener(new MouseAdapter()     
     {     public void mousePressed(MouseEvent m)
                r = new Rectangle(m.getX(),m.getY(),1,1);
          public void mouseReleased(MouseEvent m)
     addMouseMotionListener(new MouseMotionAdapter()          
     {     public void mouseDragged(MouseEvent m)
               r.width  = m.getX() - r.x;
               r.height = m.getY() - r.y;
               repaint();
               label.setText("   "+r);
public void paintComponent(Graphics g)
     super.paintComponent(g);
     if (r != null) ((Graphics2D)g).draw(r);
public static void main(String[] args )
     new DrawR();
Noah
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class DrawR extends JFrame
     JLabel label = new JLabel();
public DrawR()
     addWindowListener(new WindowAdapter()
{     public void windowClosing(WindowEvent ev)
          {     dispose();
               System.exit(0);
     setBounds(50,50,450,400);
     getContentPane().setLayout(new BorderLayout());
     Draw draw = new Draw();     
     getContentPane().add("Center",draw);
     getContentPane().add("South",label);
setVisible(true);     
public class Draw extends JPanel
     Rectangle r = null;
public Draw()
     addMouseListener(new MouseAdapter()     
     {     public void mousePressed(MouseEvent m)
               r = new Rectangle(m.getX(),m.getY(),1,1);
          public void mouseReleased(MouseEvent m)
     addMouseMotionListener(new MouseMotionAdapter()          
     {     public void mouseDragged(MouseEvent m)
               r.width = m.getX() - r.x;
               r.height = m.getY() - r.y;
               repaint();
               label.setText(" "+r);
public void paintComponent(Graphics g)
     super.paintComponent(g);
     if (r != null) ((Graphics2D)g).draw(r);
public static void main(String[] args )
     new DrawR();
}

Similar Messages

  • Draw multiple rectangles with mouse and allow exclusion of individual rectangles

    Hi,
    I have the following AS code to draw a single rectangle using mouse, but I need a different code that allows drawing multiple rectangles and the selection/exclusion of individual rectangles like a modeling tool (eg.: MS Visio).
    Can you help me?
    Thanks.

    What if I use MovieClips as the rectangle? When the click occurs, a new MovieClip is added dynamically to stage and when the user clicks right in a MovieClip's border it can be deleted.
    I'll try this way. And if you have any suggestions please let me know.
    Thanks.
    PS: This is the code I just forgot to include in the past post.
    const CANVAS:Graphics = graphics;
    var _dragging:Boolean = false;
    var _corner:Point;
    stage.addEventListener(MouseEvent.MOUSE_DOWN, setAnchor);
    stage.addEventListener(MouseEvent.MOUSE_UP, completeRect);
    function setAnchor(e:MouseEvent):void{
        if(!_dragging){
            CANVAS.clear();
            _corner = new Point(e.stageX, e.stageY);
            _dragging = true;
            stage.addEventListener(MouseEvent.MOUSE_MOVE, liveDrag);
    function completeRect(e:MouseEvent):void{
        if(_dragging){    
            _dragging = false;
            stage.removeEventListener(MouseEvent.MOUSE_MOVE, liveDrag);
            CANVAS.lineStyle(0, 0, 0);
            CANVAS.beginFill(0x222222)
            CANVAS.drawRect(_corner.x, _corner.y, e.stageX - _corner.x, e.stageY - _corner.y);
    function liveDrag(e:MouseEvent):void{
        CANVAS.clear();
        CANVAS.lineStyle(0, 0x999999);
        CANVAS.drawRect(_corner.x, _corner.y, e.stageX - _corner.x, e.stageY - _corner.y);

  • Draw a line using mouse

    Hello there:
    I'm trying to draw a line using mouse pointer: My code is:
    public class DrawLine extends JFrame implements MouseListener, MouseMotionListener
        int x0, y0, x1, y1;  
        public DrawLine()
             addMouseListener(this);
             addMouseMotionListener(this);
        public void mouseDragged(MouseEvent e)
             x1 = e.getX();
             y1 = e.getY();
             repaint();
        public void mouseMoved(MouseEvent e) { }
        public void mouseClicked(MouseEvent e){ }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited (MouseEvent e) { }
        public void mousePressed(MouseEvent e)
              x0 = e.getX();
              y0 = e.getY();           
        public void mouseReleased(MouseEvent e)
              x1 = e.getX();
              y1 = e.getY();
       public void paint(Graphics g)
                 g.setColor(Color.BLACK);
              g.drawLine(x0, y0, x1, y1);
        public static void main(String[] argv)
             DrawLine dr=new DrawLine("Test");
             dr.setVisible(true);
             dr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }when mouse is dragged, multiple lines are being drawn....
    could you else please tell me what should I've to do???
    thanks n regards...
    Dev

    You can implement the listeners on any class, even one that (implicitly) extends Object. What matters is that the listener is added to the component that needs to use it.
    That said, why do you want to extend JFrame? Are you adding functionality to the JFrame to justify extending the JFC class? Note that extending JFrame allows the users of your class to access the functionality of a JFrame, is that really indicated here?
    one class that extends JFrame, and one can draw a line on JLabel, embedded within JFrame!So you still have to override paintComponent of the JLabel, which implies using an anonymous inner class.
    Starting with the example already posted, that would be:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    public class DrawLineTest
        implements MouseListener, MouseMotionListener {
      JLabel label;
      int x0, y0, x1, y1;
      private void makeUI() {
        JFrame frame = new JFrame("DrawLineTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel("FFFF") {
          public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.BLACK);
            g.drawLine(x0, y0, x1, y1);
        label.setPreferredSize(new Dimension(500, 500));
        label.addMouseListener(this);
        label.addMouseMotionListener(this);
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new DrawLineTest().makeUI();
      public void mousePressed(MouseEvent e) {
        x0 = e.getX();
        y0 = e.getY();      
      public void mouseReleased(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
      public void mouseDragged(MouseEvent e) {
        x1 = e.getX();
        y1 = e.getY();
        label.repaint();
      public void mouseMoved(MouseEvent e) { }
      public void mouseClicked(MouseEvent e){ }
      public void mouseEntered(MouseEvent e) { }
      public void mouseExited (MouseEvent e) { }
    }Better spend more time with the tutorials, there's a separate section on writing event listeners.
    db

  • Drawing connected direct lines using the mouse

    Hallo all,
    What I want to do is, to draw connected lines on a graph using just the mouse...
    First I will define min and max values for (x,y) -graph range- using the property node...
    Then using the mouse I want to draw frequency ramps over time like in FMCW modulation... For example it will just draw the ramps by connecting several points marked by my mouse clicks on the graph. Moreover I need the (x,y) values that I click on the graph...
    Thanks,
    Ogulcan

    Hmm, this does not sound very clear. Do you want the cursor to follow the mouse even when the mouse button is up. If you have multiple cursors, which one should be followed? What should happen if you move the mouse outside the window? How do you release the cursor from the mouse when done?
    I think it is much easier if you just drag the cursors via the normal mechanism. It is most direct and intuitive. See attached LabVIEW 7.1 example. For another example of moving points, have a look at this older thread..Message Edited by altenbach on 06-28-2005 10:13 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Cursorcontrol.vi ‏45 KB

  • (HELP)!!!!How to change this code to draw a rectangle?

    * File: DrawLines.java
    * This program allows users to create lines on the graphics
    * canvas by clicking and dragging with the mouse.
    import acm.graphics.*;
    import acm.program.*;
    import java.awt.event.*;
    /** This class allows users to draw lines on the canvas */
    public class DrawLines extends GraphicsProgram
    implements MouseListener, MouseMotionListener {
    /** Private instance variables */
    private GLine line;
    /** Initializes the program by enabling the mouse listeners */
    public void init() {
    addMouseListeners();
    /** Called on mouse press to create a new line */
    public void mousePressed(MouseEvent e) {
    /** when the left button is pressed, create a zero length line */
    line = new GLine(e.getX(), e.getY(), e.getX(), e.getY());
    add(line);
    /** Called on mouse drag to reset the endpoint */
    public void mouseDragged(MouseEvent e) {
    /** and now drag that line across the canvas
    * the line will stop automatically when we lift our
    * finger from the mouse
    line.setEndPoint(e.getX(), e.getY());
    This is drawline programm, but I want to change it to rectangle, use setbounds.
    Help!

    h1. The Ubiquitous Newbie Tips
    * DON'T SHOUT!!!
    * Homework dumps will be flamed mercilessly.
    * Have a quick scan through the [Forum FAQ's|http://wikis.sun.com/display/SunForums/Forums.sun.com+FAQ].
    h5. Ask a good question
    * Don't forget to actually ask a question. No, The subject line doesn't count.
    * Ask once
        - Don't Crosspost!
        - Two people answering one question independantly is a waste of there time.
    * Don't even talk to me until you've:
        (a) [googled it|http://www.google.com.au/] and
        (b) looked it up in [Sun's Java Tutorials|http://java.sun.com/docs/books/tutorial/] and
        (c) read the relevant section of the [API Docs|http://java.sun.com/javase/6/docs/api/index-files/index-1.html] and maybe even
        (d) referred to the JLS (for "advanced" questions).
    * [Good questions|http://www.catb.org/~esr/faqs/smart-questions.html#intro] get better Answers. It's a fact. Trust me on this one.
        - Lots of regulars on these forums simply don't read badly written questions. It's just too frustrating.
          - FFS spare us the SMS and L33t speak! Pull your pants up, and get a hair cut!
        - Often you discover your own mistake whilst forming a "Good question".
        - Many of the regulars on these forums will bend over backwards to help with a "Good question",
          especially to a nuggetty problem, because they're interested in the answer.
    * Improve your chances of getting laid tonight by writing an SSCCE
        - For you normal people, That's a: Short Self-Contained Compilable Example.
        - Short is sweet: No-one wants to wade through 5000 lines to find your syntax errors!
        - Often you discover your own mistake whilst writing an SSCCE.
        - Solving your own problem yields a sense of accomplishment ;-)
    h5. Formatting Matters
    * Post your code between a pair of {code} tags
        - That is: {code} ... your code goes here ... {code}
        - This makes your code easier to read by preserving whitespace and highlighting java syntax.
        - Copy&paste your source code directly from your editor. The forum editor basically sucks.
        - The forums tabwidth is 8, as per [the java coding conventions|http://java.sun.com/docs/codeconv/].
          - Indents will go jagged if your tabwidth!=8 and you've mixed tabs and spaces.
          - Lines longer than 80 characters should be wrapped.
          - Proper indentation illustrates program logic.
    * Post your error messages between a pair of {code} tags:
        - That is: {code} ... errors here ... {code}
        - To make it easier for us to find, Mark the erroneous line(s) in your source-code. For example:
            System.out.println("Your momma!); // <<<< ERROR 1
        - Note that error messages are rendered basically useless if the code has been
          modified AT ALL since the error message was produced.
        - Here's [How to read a stacktrace|http://www.0xcafefeed.com/2004/06/of-thread-dumps-and-stack-traces/].
    * The forum editor has a "Preview" pane. Use it.
        - If you're new around here you'll probably find the "Rich Text" view is easier to use.
        - WARNING: Swapping from "Plain Text" view to "Rich Text" scrambles the markup!
        - To see how a posted "special effect" is done, click reply then click the quote button.
    If you (the newbie) have covered these bases *you deserve, and can therefore expect, GOOD answers!*
    h1. The pledge!
    We the New To Java regulars do hereby pledge to refrain from flaming anybody, no matter how gumbyish the question, if the OP has demonstrably tried to cover these bases. The rest are fair game.

  • Can you define a specific size of a Drawing Markup rectangle?

    Hi all,
    I am using Acrobat X and have been asked to find an answer to a 'problem' someone is having.
    If you have a site plan of one's property and they submit it to me for comment (as a pdf file) can I draw a box to a specific size? Say I set the 'scale ratio' to what the drawing scale is, I go to 'comments' and from the 'Drawing Markups' pane I choose 'draw rectangle; square', I then draw a rectangle to represent a shed of a specific size. I can dimension how far the rectangle/shed is to be from the property lines and I can dimension the rectangle/shed but I have to play with stretching it to get it to my desired size based on the scale I set.
    My question; is there anyway, when I am drawing the box, to either specify an x by y size or see the lenghts of their sides once I pick a corner and start to drag the box to the other corner?
    If not, would there be a java script that could accomplish this task?
    Any help would be appreciated.
    Thanks in advance.
    Paul

    Thanks Sabian, I understand that Acrobat is not a vector drawing application and I have been using all those programs (illustrator, AutoCAD, CorelDRAW etc.) for the past 20+ years. It wouldn't seem too much to ask considering that I can set a scale to my page (in Acrobat) and I can get Acrobat to give me a dimension from point A to point B based on that said scale, so why couldn't I expect to put a rectangle markup based on that same scale?
    As for the right tool? We are a municipality that is trying to make it easier for the public to submit applications online. Those submissions are in the format of a PDF because it is unrealistic to assume the everyone in the public has access to or can afford a program like AutoCAD or illustrator. Likewise it is too COSTLY to have everyone in the city have say 'AutoCAD' or even 'illustrator' to view the application documents to markup and send back.
    I believe  In 1991, Adobe Systems co-founder John Warnock outlined a system called "Camelot"[3] that evolved into PDF (from Wikipedia) and it was a way to have an independent viewing format regardless of what software application created it. I truly believe that Acrobat for what it's initial intent was that it should incorporate some of these features as it only makes sense in an evolutionary sense. Not to be a 'drawing package' but in it's markup/comments palette to expand on them.
    So keep your comments to 'no at this time acrobat does not allow this type of functionality but who knows in the future' and don't treat me as though I don't know anything about anything. In my decades of using these applications I have seen them evolve to include more functions and do more then when the product was originally released.
    I will now go on and recommend that they seriously look at Bluebeam Revu as it is not only cheaper but it has a ton more functionality specifically designed for the needs as listed above working with PDF's (and bitmap images to boot). I was just wanting to cover all bases and give all programs a fair look.
    Thanks again for your intuitive insight.
    Paul

  • Draw a rectangle on an image in an applet

    Hello
    I have an applet that has 3 buttons. Each of them creates an image, which is displayed on the screen. Now, I want to draw a rectangle on these images. Since I already have a paint method for displaying the images correctly, I would need a second paint method for the rectangle. (I can't put everything in the same paint() method, because I have an horrible resukt)
    Does anyone have an idea of a method that would be able to replace a paint method?
    Any help would be appreciated
    Thanks
    Philippe

    Have you thought about using one of your button to get the action done? You could use the Graphics method to create your object rectangle.
    Don't know if it would work but seems like a good idea to try.

  • Draw a rectangle outline with a transparent fill

    I am newbie using Elements 10.
    How do I draw a rectangle that only displays the stroke.  That is, it has a transparent fill.
    Your help would be much appreciated.
    Thanking you in anticipation.
    Roger

    On the options bar of the rectangular marquee tool, select "fixed size" and enter equal w & h values to suit.. That should give you a precise square configuration, outlined by the stroke
    Enter text on a separate layer
    Use the line tool to connect the square boxes. The line tool allows one to use arrow-heads.
    If you are still stuck, please post a representative example for additional guidance.

  • HELP! Handles missing when I draw a rectangle?!

    HELP! The handles are missing when I draw a rectangle with the rectangle tool. So I can't transform it Both Bounding box and edges are set to be visible, so it's not that! Is it a bug in the latest version? I have never had trouble with that before!

    camras,
    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) or 10.10 (Yosemite). Hopefully, the bug will be fixed soon.
    So a switch to Mavericks or Yosemite 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 or the Free Transform 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

  • Draw a rectangle from a flex app

    Hello,
    GRAND CHALLENGE (should be "hello world" that anyone should
    easily find):
    1) - a flex app with a button
    2) - when clicked the button draw the rectangle
    PROPOSED NON WORKING SOLUTION:
    draw.mxml:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>import DrawApp;</mx:Script>
    <mx:Script>
    <![CDATA[
    function drawNow():void{
    var myRectangle:DrawApp = new DrawApp();
    myCanvas.addChild(myRectangle.returnRectangle());
    ]]>
    </mx:Script>
    <mx:Canvas width="100%" height="100%"
    id="myCanvas"></mx:Canvas>
    <mx:Button label="draw"
    click="drawNow()"></mx:Button>
    </mx:Application>
    DrawApp.as:
    // ActionScript file
    package {
    import flash.display.*;
    class DrawApp extends Sprite
    public function DrawApp()
    //don't use the constructor anymore since it won't return
    the rectangle
    public function returnRectangle():Shape
    var rectAndCircle:Shape=new Shape();
    rectAndCircle.graphics.lineStyle(1);
    rectAndCircle.graphics.beginFill(0x0000FF,1);
    rectAndCircle.graphics.drawRect(125,0,550,575);
    rectAndCircle.graphics.endFill();
    return rectAndCircle;
    }//class
    }//package
    I've got an error "1034" (BTW as a bonus if anyone know how i
    can avoid to have the localized AS3 error messages so I can paste
    full error messages in English)
    CHALLENGE:
    Can someone show me how to make this wok before Silverlight2
    Beta get out?
    Thanks from francois who's mad trying to solve this "should
    be obvious hello world" for too long and who also discovered
    lately:
    - the lack of threads in AS3
    - the insane security policy around Flash Player (must
    install a proxy to access a public API...)
    - etc.
    Help please Oo

    Ok found the solution: needed to change the "Shape" object by
    a "UIComponent" object (don't know why).

  • A rectangle around my mouse cursor

    Since the last two days a rectangle around my mouse cursor is appearing. When i move my mouse and as it touches the wall of the rectangle it also moves and so my mouse cursor never comes out of that rectangle. Incidently when i login using a different account, i don't see this rectangle. It must be a program, i hope it should not be virus.
    Any solution please ?

    System preferences --> Universal Access --> Zoom Options button --> set maximum zoom to far left and/or uncheck the "Show prieview rectangle when zoomed out" checkbox
    Update:
    Here's a X Lab article on this topic:
    Black rectangle appears after Mac OS X 10.4.8 Update

  • Unable to constrain rectangle using marquee tool

    Holding down the shift key while using the marquee tool to draw a rectangle does not work. That is, the rectangle is not constrained to a square using this technique. I think the problem may be with settings for this tool. I cannot see how to restore the defaults in Preferences. Restoring the Essentials workspace to the default did not help. How can I constrain rectangles and ovals using the marquee and lasso tools? Thanks.

    Hi,
    What version of photoshop are you using?
    You can reset the defaults for one tool or all the tools by right clicking on tool icon in the tool options bar.
    That could also happen if you have something other than New Selection enabled in the tool options bar.

  • Drawing a rectangle

    I want to draw a rectangle - not a filled rectangle, I can do that but say a rectangle about 5 pixels wide that I can then drag to resize and use like a frame. The pre-defined shapes increase their line thickness as you make them bigger which is not what I want.
    I could of course draw an outer rectangle in colour and then a smaller white one inside to simulate the effect I want but I'm using transparency so I don't want a filled white area.
    Please tell me I've missed something simple!

    File>new> blank file
    Access rectangular marquee tool. In the tool's option bar, one can establish a fized size
    Edit>stroke. The width of the stroke can be configured in pixels.
    Any intervening color can be removed by selecting with magic wand tool

  • Resizing JPanels using a mouse?

    I have a program that draws on a BufferedImage, but I want to be able to resize the image. At the minute it is on a JPanel, which in turn will be placed in a JScrollPane, but I was wondering if there was a way of resizing the JPanel using the mouse, like you can with a JFrame.
    If not, is there another way I can do this?
    Thanks in advance.

    Thanks for the replies so far.
    I'm trying to write a basic drawing program, and the plan was that the image size (and also its observer component) are not fixed and are independent of the frame (or other component) in which they are located. That was where I assumed the JScrollPane would come in, as this way all the image can be accessed if I make the main window small, for example.
    I've not had a lot of experience doing this kind of thing though, so I'm still not sure of the best way to go about it. As I see it, the JSplitPane is only resizable in one axis. A JSplitPane can effectively be resized in both axes by nesting JSplitPanes, but I feel that this will look a bit untidy.

  • How do you draw a rectangle in JavaScript?

    I am developing an ASP.NET application. There is an image on one of my pages. Users need to be able to draw a rectangle on which part of the image they want to zoom-in to. Basically, when the user clicks on the image, that XY location will be one corner of the rectangle. As the user moves the mouse over the image, I want to be able to show the rectangle. Once they let go of the mouse, I need to send those coordinates to the server and perform the zoom operation.
    Does anyone have code that does this?

    How, exactly, did you decide that a forum called "New
    To Java Technology" was the place to ask this
    question??Well he is clearly new to java technology since he dosn't realize that java and javascript are two completley different things.

Maybe you are looking for

  • Purchase Order triggering Sales Order using Inbound Idocs

    Hi All, Can any one explain the flow of Purchase Order triggering Sales Order using Inbound Idocs..?? Thanks & Regards Anoop

  • Radius authentication for the browser-based webtop

    Hiya all, With help of the radius-authentication module for apache (http://www.freeradius.org/mod_auth_radius/) and web-authentication it is possible to use radius-authentication for the classic-webtop. Has anyone got Radius authentication working fo

  • Dummy profit center-company code assignment

    Dear Experts, How to deactivate company code assignment in dummy profit center? by mistake we selected one company code in dummy profit center, for which profit center accounting is not applicable, so we tried to remove the check box in profit center

  • The strange behaviour of the notification

    Coherence 3.3.1/389      .Net API 3.3.1.2      I have C++ GUI client with grid. It shows in the grid all updates from Coherence.      I have also the 'server' application, which inserts objects into Coherence (1 - 2 per second).      I use 'near-sche

  • How to cancel a Nomination?

    Hi All, Can anybody please tell me what is the process to CANCEL a Nomination which has a "DELETION Indicator" set. The Deletion indicator is set @ the header level due to which the client is not able to cancel the Nomination. There is no ticket or a