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

Similar Messages

  • Drawing on a Canvas

    I know this may seem trivial, but for some reason I am having trouble drawing rectangles on an Canvas. Either I get that the Graphics object is null or the objects just don't show up. Any suggestions? Any help would be very much appreciated. Here are the relevant parts of my code:
    This code is in a class that extends Canvas:
    public void paint(Graphics g) {
    g.setColor(Color.black);
    g.fillRect((int)obstacleArray[0][0], (int)obstacleArray[i][0][1], tempwidth, tempheight);
    g.drawImage(myImg, 0, 0, this);
    } // end paint

    Nevermind - I solved my problem. I was sending in a height of zero. :)

  • 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

    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());
    }

  • 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.

  • Draw Rectangle with red border and transparent center

    I need a little help on the rectangle object.  I need to draw a rectangle with a transparent middle and a red boarder with a thickness of 2:
    Code:
    private void InitializeRectangle(Rectangle rectangle, CellLayoutBox cellBox)
    rectangle.Fill = new SolidColorBrush(Colors.Transparent);
    rectangle.StrokeThickness = 1;
    rectangle.Width = cellBox.Width;
    rectangle.Height = cellBox.Height;
    Canvas.SetLeft(rectangle, cellBox.Left);
    Canvas.SetRight(rectangle, cellBox.Top);
    I know I am missing the mark here, but it I can't seem to get a rectangle with a transparent fill and stroke of a different color even if I change the Colors.Transparent to another color. Any help is appreciated.

    @katghoti,
    Thanks for sharing the result back to forum.
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Drawing mc with canvas on it

    Hey,
    I got a problem with displaying canvas on mc, which is drawn on BitmapData object. Code is more or less:
    var can:Canvas = new Canvas;
    can.setStyle("backgroundColor","blue");
    can.width = 100;
    can.height = 100;
    can.x = 100;
    can.y = 100;
    var mc:MovieClip = new MovieClip
    mc.addChile(can);
    var bd:BitmapData = new BitmapData;
    bd.draw(mc);
    this.beginBitmapFill(bd,new Matrix(),false,false);
    this.graphics.endFill();
    And I dont see the canvas. ValidateNow() or callLater doesn't help either.
    On the other if I add a sprite instead of canvas I can see this sprite on screen.
    What should I do and why validateNow() doesn't help in this case?

    thanks for that :)
    my problem is that the nodes are placed inside a panel to appear as draggable entities on the GUI interface using the google web toolkit. that way I need to somehow not put the JPanels in a JFrame but in the panel created by google web toolkit, which I think you cannot do?

  • 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

Maybe you are looking for

  • Varience Report

    Dear Friends My client needs to run a report with following information. Production Order, Material, Standard Price, Actual Cost, Total Varience. Please provide me answer for this. For right answer full points will be given. This will be one way of t

  • Joining mime attachments

    I have just received a handful of emails that were sent from Windows/Outlook Express and it looks like they are a very large file broken up into three pieces (another one is 21 pieces). When I look at the email all I see is: Partial message, part 1 o

  • My inbox says its receiving 200 mails but only 3 in the inbox, why is this? It also says its sending 3 when I am only sending 1.

    When using mail the system shows information that it has received mail (today it said 300) but only 2 or 3 come up in the inbox. It never used to do this. Why? Similarly when sending mail it says sending 3 of 3 when I am only sending 1 email.

  • Will you ever have to use an InfoSource in BI 7?

    Hi, for all the review that I've made so far, one thing that still confuses me is the role of an InfoSource in a BI 7.0 environment. Will you ever have to use an InfoSource in BI 7? Any situation that calls for that? Thanks

  • Extended use of iSight (eg. Skype) makes screen glitch

    Recently, my computer (2010 17" MBP, Snow Leopard) started having problems when I use the camera for ~1+ hour while Skyping. The other person will see me appear and disappear in rapid succession, then go dark (but the green dot stays on so the camera