How to draw rectangle using JAVA

Posted on 2009-04-28
Last Modified: 2013-12-22
I want to draw rectangle in java.
This rectangle should be defined by the end points of one of the diagonals.
I need to draw rectangle like this:
                        If I click "Draw Rectangle" button and click first point on the screen, the rectangle formed by clicked point and the current mouse location is then displayed in red until the second mouse click. After that the rectangle is displayed in the standard color.

Could you please tell me how to draw the rectangle using above information in java?
Once I click first mouse click, rectangle formed by mouse click and moving rectangle with mouse until click the second mouse click then the rectangle formed completely.
Question by:easy_life
    LVL 92

    Accepted Solution

    LVL 12

    Expert Comment

    LVL 2

    Expert Comment

    And finally, to draw rectangles:
    Scroll down to the Rectangle bit. You'll need one corner, and the height and width of the rectangle.

    So to sum it up:
     * Make a MouseListener (that extends MouseAdapter) to listen for the clicks
     * Make a MouseMotionListener (that extends MouseMotionAdapter) to follow the mouse after the first click.
     * Store the resulting coordinates.
     * Draw the rectangle using those coordinates (in the paint method)

    The 2D graphics trail is very helpful if you want to learn more about graphics:

    Author Closing Comment

    Thank you for your help.

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
    Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
    Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
    The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now