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

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

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

  • 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;");

  • Draw polygon in applet

    HI,
    I want to be able to draw polygon using java applet. I have code to draw poly in an applet but I am wondering if the java tool can draw directly on html image not on image inside of applet.
    Please help
    Ying

    You can generate a gif which is displayed inside a HTML screen.
    Note: HTML does not support polygon drawing so you cannot write HTML to draw a polygon. Unless you want a rectangle (use a table :)

  • Newbie question - Drawing objects in applet

    Hi,
    I'm pretty new to java, and I have a small problem involving drawing a rectangle on a java applet.Firstly this is not a plea for someone to help me with this peice of work, I just need pointing in the right direction.
    Ok the problem.
    I am creating a program that ask the user to input a height value, the program will then do a calculation and create a golden ratio width. The type of both the height and the width are double.
    This is where the problem starts. The next thing I need to do is make the program draw the rectangle using the user inputted height and the calculated width.
    I have a feeling that the problem has occured because I haven't converted the type double into a int type.
    Here is my code
    import java.awt.*;
    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    * Class Test - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class Test extends JApplet
        // instance variables - replace the example below with your own
       double sum, number1;
       int height;
       int width;
         * Called by the browser or applet viewer to inform this JApplet that it
         * has been loaded into the system. It is always called before the first
         * time that the start method is called.
        public void init()
            String firstNumber;
            double sum1;
            firstNumber = JOptionPane.showInputDialog("Please enter the height" );
            number1 = Double.parseDouble( firstNumber );
            sum1 = (Math.sqrt(5) + 1) / 2;
            sum = number1 * sum1;
            int height = (int)number1;
            int width = (int)sum;
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            // provide any initialisation necessary for your JApplet
         * Called by the browser or applet viewer to inform this JApplet that it
         * should start its execution. It is called after the init method and
         * each time the JApplet is revisited in a Web page.
        public void start()
            // provide any code requred to run each time
            // web page is visited
         * Called by the browser or applet viewer to inform this JApplet that
         * it should stop its execution. It is called when the Web page that
         * contains this JApplet has been replaced by another page, and also
         * just before the JApplet is to be destroyed.
        public void stop()
            // provide any code that needs to be run when page
            // is replaced by another page or before JApplet is destroyed
         * Paint method for applet.
         * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // simple text displayed on applet
            g.drawRect( 15, 10, 270, 20 );
            g.drawString("The sum is " + number1, 25, 25 );
            g.drawRect( 100, 100, height, width);
         * Called by the browser or applet viewer to inform this JApplet that it
         * is being reclaimed and that it should destroy any resources that it
         * has allocated. The stop method will always be called before destroy.
        public void destroy()
            // provide code to be run when JApplet is about to be destroyed.
         * Returns information about this applet.
         * An applet should override this method to return a String containing
         * information about the author, version, and copyright of the JApplet.
         * @return a String representation of information about this JApplet
        public String getAppletInfo()
            // provide information about the applet
            return "Title:   \nAuthor:   \nA simple applet example description. ";
         * Returns parameter information about this JApplet.
         * Returns information about the parameters than are understood by this JApplet.
         * An applet should override this method to return an array of Strings
         * describing these parameters.
         * Each element of the array should be a set of three Strings containing
         * the name, the type, and a description.
         * @return a String[] representation of parameter information about this JApplet
        public String[][] getParameterInfo()
            // provide parameter information about the applet
            String paramInfo[][] = {
                     {"firstParameter",    "1-10",    "description of first parameter"},
                     {"status", "boolean", "description of second parameter"},
                     {"images",   "url",     "description of third parameter"}
            return paramInfo;
    }Thanks for any suggestions.

    Hey ProjectMoon, I had to re-register because it wouldn't let me log back in for some reason.Anyway thanks for the information, i'm trying to get my head around what you said, also I tried printing the height in the drawstring,and as you predicted I got a value of 0. I just wanted to know wjat you mean by:
    "You want to store your height and width in the instance variables you have declared."
    Because I thought I had declared them at the top of the page
    public class Test extends JApplet
        // instance variables - replace the example below with your own
       double sum, number1;
       int height;
       int width;One further question, is the method I used to convert double to int correct?
    int height = (int)number1;
    int width = (int)sum;Thanks again for the time you have spend answering the questions.

  • Help need in Drag and drop the Lines and rectangle in applet

    hi
    i want to create a simple paint applictaion which is capable of draw lines, rectangle, images etc. after that lines and other thinks can be moveable and rotate and scaling also.
    the major restrictions in its implemented only in jdk1.1.
    so if you people found any solutions or sample codings or application(this one is best) send it to [email protected]
    thanks in advance
    Giri

    the major restrictions in its implemented only in
    jdk1.1.Why!

  • 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

Maybe you are looking for

  • Reading XML object from Request object

    Hi, We are using Flash in our web application in which we are sending an XML object using HTTP post method to a JSP where we need to parse the XML object and get the values. Can anyone tell how we can do it?

  • Please help! Safari keeps hanging/not responding and freezes everything else up.

    I've got a mid-2009 MacBook Pro running OS X Snow Leopard (10.6.8) and Safari (5.1.9) keeps hanging/crashing. I'm afraid I'm not very good with these things so I'll just have to tell the story... It's happening when I start up Safari, either the home

  • Calling from java buttons in an applet

    ok i made this program here and now i'am tryin to call certain certain classes from each button. i can't figure out how to do that. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JDemoGridLayout extends JApplet JLabel

  • How can i change the format of output captured footage using DSR-11 in Premiere Pro CS5.5?

    Hi. I am using Premiere Pro CS5.5, capturing footage off a mini-DV casette (NOT HD) using a Sony DSR-11. All is well with that, except for that the output is an .avi rather than MP4 (H264). I am under the impression that H264 with the extension of .M

  • Hijack of RAW files by PDF reader

    suddenly this evening all my raw files got Acrobat logo. on the 'open with' panel I was unable to choose Photoshop, but if I go to PS I can locate and open the file. I cannot choose Photoshop on the "open with" panel for any file (jpeg,tiff, arw) I h