Draw rectangle

Hi,I want to use mouse to draw a rectangle.But my code doesn't work.Could anyone have a look and make it work please?Heaps of thanks!
import javax.swing.JInternalFrame;
import java.awt.Cursor;
import java.io.File;
//for inner class
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
* Testing drawing rectangle
public class TestDraw extends JInternalFrame
private Container c;
public TestDraw(String name) {
super(name,true,true,true,true);
//Set the window size or call pack...
setSize(300,300);
c = this.getContentPane();
c.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
c.addMouseListener(new MouseMonitor(this));
setVisible(true);
}//End of constructor
public static void main(String[] args)
TestDraw td = new TestDraw("test");
     TestGUI tg = new TestGUI(td);
private static class TestGUI extends JFrame
     public TestGUI(JInternalFrame jif)
          setBounds(100,100,400,400);
          Container c = getContentPane();
c.add(jif);
setVisible(true);
/********************MouseMonitor INNER CLASS********************/
     private class MouseMonitor extends MouseAdapter
          private int clickedX,clickedY,releasedX,releasedY;
          private JInternalFrame j;
          public MouseMonitor(JInternalFrame ji)
this.j = ji;
          public void mouseClicked(MouseEvent event)
          clickedX = event.getX();
          clickedY = event.getY();
          }//End of mouseClicked()
          public void mouseReleased(MouseEvent event)
               releasedX = event.getX();
               releasedY = event.getY();
System.out.println("clickedX="+clickedX);
System.out.println("clickedY="+clickedY);
System.out.println("releasedX="+releasedX);
System.out.println("releasedY="+releasedY);
Node node = new Node(clickedX,clickedY,releasedX,releasedY);
node.setColor(Color.RED);
               j.paintComponent(node);
               j.repaint();
               j.validate();
/********************Node INNER CLASS********************/
class Node extends Rectangle
private Color color;
private int left, top, width, height;
public Node( int x, int y, int width, int height)
setBounds(x, y, width, height);
repaint();
void setColor(Color color) {
// Set the color of this shape
this.color = color;
public void setBounds(int left, int top, int width, int height) {
// Set the position and size of this shape.
this.left = left;
this.top = top;
this.width = width;
this.height = height;
void draw(Graphics g) {
g.setColor(color);
g.fillRect(left,top,width,height);
g.setColor(Color.black);
g.drawRect(left,top,width,height);
/**************************END INNER CLASS**********************/
          public void paint(Graphics g)
               Graphics2D g2 = (Graphics2D) g;
               g2.setPaint(Color.red);
               g2.draw3DRect(clickedX,clickedY,releasedX,releasedY,true);
}

Fabulous program!
I'd like to add more function,but stuck at the right click when the mouse pointing to the node.I want to show the popup menu when user right-clicks at the node,but show error message when he left-click(means he try to draw another node on the top of that node).
The program seems act properly when mouse is pressed,but error dialog pops and blocks the mouseReleased action.Thanks in advance!
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
public class ShapeFrame1 extends JInternalFrame {
     private List<Node> nodes;
     private Node selected;
     private Point start;
     private boolean drawing;
     public static void main(String[] args) {
          ShapeFrame1 sf = new ShapeFrame1("Shape Test");
          JFrame frame = new JFrame("Shape Test");
          frame.setBounds(100,100,640,480);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(sf);
          sf.pack();
          sf.setVisible(true);
          frame.setVisible(true);
     public ShapeFrame1(String title) {
          super(title,true,true,true,true);
          setContentPane(new NodePanel());
          nodes = new ArrayList<Node>();
          getContentPane().addMouseListener(new MouseMonitor());
          getContentPane().addMouseMotionListener(new MouseMonitor());
     protected Node createNode(Point start, Point end) {
          return new Node(start.x, start.y,end.x - start.x, end.y - start.y, Color.BLACK);
     protected Node getNodeAt(Point location) {
          for(Node node : nodes)
               if(node.contains(location))
                    return node;
          return null;
     class NodePanel extends JPanel {
          public void paintComponent(Graphics g) {
               for(Node node : nodes)
                    node.paint(g);
               if(drawing) { // User is currently drawing
                    Graphics2D g2 = (Graphics2D)g;
                    g2.setColor(Color.BLUE);
                    g2.draw(createNode(start, getMousePosition()));
               else if (start != null){
     class Node extends Rectangle {
          private Color color;
          private String name;
          Node(int x, int y, int width, int height, Color color) {
               super(x, y, width, height);
               this.color = color;
          public void paint(Graphics g) {
               Graphics2D g2 = (Graphics2D)g;
               if(selected != null && selected.equals(this))
                    g2.setColor(Color.BLUE);
               else
                    g2.setColor(color);
               g2.draw(this);
          void setName(String n){
               this.name = n;
          String getName(){
               return this.name;
     class MyPopupMenu extends JPopupMenu{
          MyPopupMenu(){
               createDefaultMenuItem(this);
          private void createDefaultMenuItem(JPopupMenu popup) {
               JMenuItem item;
               item = new JMenuItem("cut");
               popup.add(item);
               item = new JMenuItem("copy");
               popup.add(item);
               item = new JMenuItem("paste");
               popup.add(item);
               popup.addSeparator();
               item = new JMenuItem("Add Node Name");
               popup.add(item);
     class MouseMonitor extends MouseAdapter implements MouseMotionListener {
          private MyPopupMenu popup = new MyPopupMenu();
          public void mousePressed(MouseEvent evt) {
               checkPopup(evt);
               Node node = getNodeAt(evt.getPoint());
                    if (node != null)
                         JOptionPane.showMessageDialog(
                               new JFrame(),
                          "Node exists.Please choose another location!",
                          "ERROR",
                          JOptionPane.ERROR_MESSAGE);
                    else
                         start = evt.getPoint();
          public void mouseReleased(MouseEvent evt) {
               checkPopup(evt);
               if(drawing) {
                    Node node = createNode(start, evt.getPoint());
                    nodes.add(node);
                    setCursor(Cursor.getDefaultCursor());
                    drawing = false;
               } else {
                    // User isn't drawing, so select a Node if there is one
                    Node node = getNodeAt(evt.getPoint());
                    selected = node;
               repaint();
          public void mouseMoved(MouseEvent evt) {}
          public void mouseDragged(MouseEvent evt) {
               drawing = true;
               setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
               repaint(); // User is currently drawing, so repaint the view
          private void checkPopup(MouseEvent evt){
               if (evt.isPopupTrigger()){
                    popup.show(evt.getComponent(),evt.getX(),evt.getY());
}

Similar Messages

  • Draw rectangle in plot

    How can i draw rectangle in graph
    with Component works++?

    Annotations were introduced to the C++/ActiveX graph in Measurement Studio 6.0. This is the best way to draw a rectangle.
    Details:
    CNiAnnotation:hape is a property of type CNiShape. CNiShape::Type is an enumeration, one value of which is CNiShape::Rectangle. Use CNiShape::XCoordinates and CNiShape::YCoordinates to specify the location and size of the rectangle. Use CNiAnnotation::CoordinateType to specify whether the coordinates of the rectangle are in axis units or in pixels relative to plot area or screen area.
    If you cannot upgrade to Measurement Studio 6.0, you could consider using 2 cursors as a workaround.
    David Rohacek
    National Instruments

  • Control of drawing rectangle (links, cropping, etc.)

    For some reason, I don't have precise control over drawing rectangles (for adding links or cropping) to PDF documents in Acrobat 9.0 Pro. I used to!
    I can still create these boxes, but they are much more rigid control-wise, almost like a "snapping" feature is activated. If links are close together on the PDF, it's hard to make them so they don't overlap.
    Does this make sense? Advice?

    Under View make sure Snap to grid is turned off.

  • Draw rectangle at the Intensity graph (position where it is clicked )

    I am able to extract coordinates using mouse down and mouse up event structure but unable to draw the rectangle at the specified positions.I am getting coordinates at mouse down and mouse up event  in these bounds.I want to draw a rectangle at the position of coordinates but unable to do so.
    Solved!
    Go to Solution.
    Attachments:
    Draw Rect on Intensity Graph.vi ‏21 KB

    One more thing, since you're using the Draw Rectangle function you need to deal with the cases where the rectangle is not drawn from top left to bottom right. You have to make sure the minimum X value goes to the LEFT input and the minimum Y value goes to the TOP input of the rect terminal of the Draw Rectangle vi. Use the Max & Min function from the comparison palette for this.
    Ben64
    Attachments:
    Draw Rect on Intensity Graph3.vi ‏16 KB

  • Drawing rectangles in Applet

    Hi all.
    I am looking to manipulate this code so that the user can draw rectangles rather than dragging dots to the screen.
    any ideas how I would do this?
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class L10DragMouse extends Applet {
         private int xValue = -10, yValue = -10;
         public void init()
              addMouseMotionListener(new MotionHandler(this) );
         public void paint( Graphics g )
              g.drawString("Drag the mouse to draw", 10, 20);
              g.fillOval(xValue, yValue, 4, 4);
         public void update(Graphics g) {paint(g); }
         public void setCoordinates(int x, int y)
              xValue = x;
              yValue = y;
              repaint();
    class MotionHandler extends MouseMotionAdapter {
         private L10DragMouse dragger;
         public MotionHandler(L10DragMouse d) {dragger = d;}
         public void mouseDragged( MouseEvent e )
              { dragger.setCoordinates(e.getX(), e.getY() ); }
    }

    Okay it is compiling for me now but is not allowing me to create rectangles when the applet opens up. Just a plain page and no graph / rectangle when I drag mouse.
    any ideas?
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class L10DragMouse extends Applet {
         private int xValue = -10, yValue = -10;
            private int origX = -10, origY = -10;
         public void init()
              addMouseMotionListener(new MotionHandler(this) );
         public void paint( Graphics g )
              g.drawString("Drag the mouse to draw", 10, 20);
              g.fillRect(xValue, yValue, origX, origY);
         public void update(Graphics g) {paint(g); }
         public void setCoordinates(int x, int y)
              xValue = x;
              yValue = y;
              repaint();
            public void setOriginalCoordinates(int x, int y)
                origX = -10;
                origY = -10;
    class MotionHandler extends MouseMotionAdapter {
         private L10DragMouse dragger;
         public MotionHandler(L10DragMouse d) {dragger = d;}
         public void mouseDragged( MouseEvent e )
              { dragger.setCoordinates(e.getX(), e.getY() ); }
            public void mousePressed( MouseEvent e )
                    { dragger.setOriginalCoordinates(e.getX(), e.getY() );}
    }

  • Draw rectangle with rmi

    Dear friends
    I do I draw a simple square in rmi?
    thanks

    RuiAranhaJava wrote:
    ejp...posting an interface doesn't help and I don't want no one to do my work...
    The simple question is to draw a rectangle or circle in a frame...but one of the problems is that draw (Graphics g) is abstract and must be implemented in a abstract class (I can't even declare the function).
    what I really need is a small example to understand how to do this... I really want to understand...
    Thankssounds like you would be better off posting in the AWT or "new to java" forums. you are currently posting in the RMI forums which is for questions related to remote communication, not questions related to drawing rectangles. once you figure out how to draw a rectangle, if you still need some sort of remote communication help, i'd recommend reading some RMI tutorials. then, if you have a specific question related to remote communication in java, come back here and ask it.

  • MFC: Draw rectangle inside a rectangle

    Hi,
    I have drawn a rectangle:
    dc.Rectangle(10,10,200,100);
    Now i want to draw rectangle inside it by reducing 10 from each side. i.e the new rectangle will be: CRect(20,20,190,90).
    I am manually adjusting the co-ordinate, Is there any API to do this.
    offsetRect() is not solving my issue.
    Thanks

    Hi,
    I have drawn a rectangle:
    dc.Rectangle(10,10,200,100);
    Now i want to draw rectangle inside it by reducing 10 from each side. i.e the new rectangle will be: CRect(20,20,190,90).
    I am manually adjusting the co-ordinate, Is there any API to do this.
    offsetRect() is not solving my issue.
    Thanks
    Just write yourself a function and use it as needed. Programming is not manual work; the computer does the heavy lifting.
    Edit: Actually, I think CRect::DeflateRect() does what you want.
    David Wilkinson | Visual C++ MVP

  • Draw rectangle and apply fill color

    Hi
    anyone help me to draw rectangle outside artboard and apply fill color
    i want to draw 10 rectangle of same size and apply fill color using javascript
    Thak you
    appu

    Now that I am addressing the path items and text items of the group separately I am having some success. Now I am having difficulty getting the correct terms for assigning a Spot Color to the file. Here is a piece of the script.
    This works:
    tell application "Adobe Illustrator"
    set openDoc to document 1
    set ftClr1 to (first group item whose note is "Front3") of openDoc
    set ftClr1Paths to path items of ftClr1
    repeat with thisPath in ftClr1Paths
    set fill color of thisPath to {red:255}
    end repeat
    set textFrames to text frames of ftClr1
    repeat with thistext in textFrames
    set fill color of every line of thistext to {red:255}
    end repeat
    end tell
    Need help to set the fill color to a Spot Color that already exists in Swatches.
    Thanks
    Nick

  • I want to draw rectangle like corelDraw?

    i want to draw rectangle just like corelDraw?
    so any body know about how to draw such things please tell me

    Checkout Graphics and Graphics2D.

  • Is there any way to draw Rectangle on Command Prompt

    how to draw a rectangle on command Prompt without using Applet andJFrame

    No real solution for that but this one (and similar):
    System.out.println("&#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;\n" +
    "&#9474;            &#9474;\n" +
    "&#9474;            &#9474;\n" +
    "&#9474;            &#9474;\n" +
    "&#9474;            &#9474;\n" +
    "&#9492;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9496;");

  • 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

  • Draw Rectangle to Canvas ?

    I am finding that working with drawing shape in Java is a bit hard to understand. I am hoping someone can help me out. I have wanting to draw a simple Rectangle to a Canvas. I am hoping that will give the user the look that a Rectangle has been drawn to the screen and not inside of a JFrame or anything like that.
    Here is my code that does not seam to work.
    Canvas can;
    Graphics g2;
    Rectangle r;
    public void drawShape()
           can = createCanvas();
           g2 = can.getGraphics();
           g2.drawRect(0, 0, 640, 480);
    //create canvas that I call from another class
    public Canvas createCanvas( )
              r.width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
              r.height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
              r.x = 0;
              r.y = 0;
              if(box == null)
                   box = new Canvas();
                   box.setBounds(r);
              return box;
         }

    simple demo, might start you off
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JPanel p = new JPanel(){
          public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawString("alt-F4 to close",400,300);
            g.drawRect(300,200,300,200);
        p.setBackground(Color.WHITE);
        JFrame f = new JFrame();
        f.getContentPane().add(p);
        f.setUndecorated(true);
        GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(f);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }more reading here
    [http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html]
    and this
    can.getGraphics();is generally a very bad way to do it

  • What is the easiest way to draw rectangles in PS ?

    What is the best and easiest way to draw the outline of a geometric shape in PS ?
    I want to be able to control the line thickness.
    I do not want to use the superimposition of on slightly smaller rectangle over another to make the outline....
    .....too ify and too time consuming.
    The line tool from the tool palette is also ungratifying and not the answer.
    There must be a better way.
    Thanx

    Not getting it Chris.
    Could you paste in an image explaining what it is you do after setting the fill capacity
    to zero because when I did that the rectangle and everything else disappeared.
    This is what was left of my rectangle when the fill opacity was 32%
    david

  • Third-part tool to draw rectangle on block diagram

    I know there was once a third-party tool that enabled me to draw a nice double-bordered rectangle on the block diagram.  Yes, that is the block diagram not the front panel.  It was very useful for making annotations and denoting functional groupings.  Does anyone know what that might be?  I have installed VI Package Manager and gone through everything I can think of without finding it.
    Unfortunately, the documentation for these potentially very useful add-ons is poor.  The "Get info" is terse to the point of useless and clicking on "Product Homepage" rarely gets you more than a logo, not informative.  Surely, there must be more details somewhere.
    Solved!
    Go to Solution.

    I don't know what tool you're referring to. What does this logo look like? Perhaps someone may recognize it.
    What's wrong with the flat frame?
    Attachments:
    flat frame.png ‏33 KB

  • Draw rectangle onto JLabel

    Hi,
    I'm using a JLabel as a placeholder for an image (the board on wich a boardgame will be layed). But now
    I need to draw an red rectangle on this image..
    Can anyone help and give more information about how this can be done?
    Regards,
    Jeroen

    Read the Swing tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html
    There are sections on "Using Borders" or "Custom Painting". I don't fully understand your requirement, so I'll let you decide which approach is best.

Maybe you are looking for

  • How to use Hyperlink in BSP page

    Hi, I have a hyperlink content in a table in one field. The link content is generated at the runtime, I mean it is not constant every time. It is different for different records in the table. I want to navigate to that link( a new window ) when click

  • Can I start over in iPhoto?

    I transferred all photos from a pc and there was a lot of duplication.  These photos went into iphoto before I cleaned up the images file.  Windows will not allow for duplicate file names, but Mac seems to have not problem with files having the same

  • How do I remove the icon that appears while scrolling that makes my scrolling go wild

    When I am trying to scroll up and down a page a small upright oval appears wit a line across the middle and a dot in the top and bottom half, My scrolling then goes wild, what is this symbol called and how do I remove it from Firefox on my Mac? I hav

  • Standard event at end of report

    Hi guys, This is a really complex question and my manager expects me to know the answer to this just 'cause I'm certified, but I think this is very expert knowledge. The question is: Is there a standard event triggered at the end of EVERY ABAP report

  • PO Error in Transfer for Direct Procurment

    Hi All, we are running SRM 550 and are at SP15. We need to get SRM to order Direct Materials for a storage location in our ECC system. So far all the config has been done,  materials transferred, storage locations defined in Org structure extended at