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

Similar Messages

  • How to draw a line using JSP?

    Does anyone know how to draw a line using a JSP? Any help is much appreciated.
    Regards,
    Navin Pathuru.

    Graphics classes are useless in JSP files; you can only output HTML tags to the client browser.
    You should be able to give just about any presentation look that you need with HTML and CSS. Have you played with styles? Here's a simple example that works in IE 5+ and Netscape 4.7:
    <HTML>
    <HEAD>
    <STYLE>
    .box {
    border-style:solid;
    border-color:black;
    border-right-width: 1px;
    border-top-width: 1px;
    border-left-width: 1px;
    border-bottom-width: 1px;
    .line {
    border-right-width: 1px;
    border-top-width: 0px;
    border-left-width: 0px;
    border-bottom-width: 0px;
    border-style: solid;
    border-color: red;
    width:1pt;
    height:100%;
    </STYLE>
    </HEAD>
    <BODY>
    <TABLE CELLPADDING=1 CELLSPACING=0 WIDTH=100>
    <TR><TD ALIGN=CENTER><SPAN CLASS="box">Field One</SPAN></TD></TR>
    <TR HEIGHT=50><TD ALIGN=CENTER><SPAN CLASS="line">�</SPAN></TD></TR>
    <TR><TD ALIGN=CENTER><SPAN CLASS="box">Field Two</SPAN></TD></TR>
    <TR HEIGHT=50><TD ALIGN=CENTER WIDTH=50%><SPAN CLASS="line">�</SPAN></TD></TR>
    <TR><TD ALIGN=CENTER><SPAN CLASS="box">Field Three</SPAN></TD></TR>
    </TABLE>
    </BODY>
    </HTML>
    Have fun!

  • Getting Dynamic XPOS and YPOS for drawing the line in MAIN window in SAP Script using BOX command

    Hi Experts,
    I am trying to draw a line using the BOX command in the main window.
    /:         BOX HEIGHT 0 TW FRAME 10 TW INTENSITY 100
    I want to draw a line in XPOS and YPOS dynamically..
    Is there any way to find such I can draw a line dynamically after triggering a Text element. or determine the XPOS and YPOS dynamically such that I can draw a line in an intended position dynamically.
    Thanks in Advance
    Regards
    Rajesh Chowdary Velaga

    Any update on this ??

  • Drawing a line in java 1.4

    I am drawing a line using the method
    drawPolyline(int[],int[],int) of the Graphics class.
    It works fine in all cases except when i try to draw
    an exactly vertical line or an exactly horizontal
    line. In these 2 case, it does not draw a line at all.
    All. i can see are the 2 selection end points.
    This works fine in jdk1.3 but not in jdk1.4
    Please lemme know ASAP as to what the problem and what i should do?
    Thanks
    Jatin

    You forgot to add this to your paint() code ...
    g.setColor(Color.BLACK)
    You'll never see anything drawn unless you set a color different thatn background.
    This works, I added code so you can run it in a frame too because I don't want to be bothered with dealing with applets and html files;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Lab11 extends Applet implements MouseListener, MouseMotionListener {
        int x0, y0, x1, y1;
        //public void init() {
             public Lab11() {
             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();
         System.out.println("Mouse pressed at: (" +
                      x0 + ", " + y0 + ")" );
        public void mouseReleased(MouseEvent e) {
         x1 = e.getX();
         y1 = e.getY();
         System.out.println("Mouse released at: (" +
                      x1 + ", " + y1 + ")" );
         this.repaint();
       public void paint(Graphics g) {
            g.setColor(Color.BLACK);
         g.drawLine(x0, y0, x1, y1);
        public static void main(String[] argv)
             JFrame f = new JFrame("Test");
             f.getContentPane().add(new Lab11());
             f.setVisible(true);
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • Here are my last 3 duke dollars.  Can someone please help me draw a line?

    I have been BEATING my head on this for well over a week now. I'm new to Java2D and I cannot find even one example of this simple little thing that I am trying to do. Not one.
    All I want to do is draw an image, zoom that image, then draw some lines on that image, and then zoom it and have those lines show up where they should.
    For example, we have an image which has been zoomed. No lines are yet drawn on it.
    A line is added.
    The image is then zoomed in or out one more time.
    How do we get the line to remap to the newly zoomed image?
    What I am doing is:
    0) Load up an image from a file.
    1) Create a zoomed image by using the Image.getScaledInstance() method.
    2) Create a BufferedImage with the width and height of the image AFTER the zoom has taken place.
    3) Create a Graphics2D object by the createGraphics from this BufferedImage.
    4) Place the image into the BufferedImage by doing a BufferedImage.drawImage
    5) Select two points to be the start and end of the line.
    6) Draw the line using Graphics2D.drawLine(start.x, start.y, end.x, end.y).
    7) Zoom the image again (using the Image.getScaledInstance() method.
    8) Create a new ImageIcon using the image from above and override its paintIcon method like this:
    ImageIcon newIcon = new ImageIcon(newImage) {                       
    public void paintIcon(Component c, Graphics g, int x, int y)
    super.paintIcon(c, g, x, y);
    zoom(); //<---- ZOOM call
    Now in the zoom routine, what do I need to do to get the lines to draw at the proper location and size?
    Remember, the points of the lines (stored in a list as home grown line objects) are in screen coordinates, not image coordinates since they are just click points
    Note that when I use these points to draw a line, all is well (the line gets drawn where it should), but I have problems when I zoom the image.
    Thanks!

    Below is the documentation and method signature of
    Graphics.drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer);The important thing to note is that it does scaling on the fly if the size dictated by the source co-ordinates is defferent than the size dictated by the destination co-ordinates. The source image is always left un-touched.
    So basically your visual data is located in an offscreen image. You can draw a line on that. Then create a new image, get it's graphics and call drawImage(original_image, co-ordinates that cause it to scale how you like).
    Then you can draw lines on the 2nd image, create a 3rd, ...etc
         * Draws as much of the specified area of the specified image as is
         * currently available, scaling it on the fly to fit inside the
         * specified area of the destination drawable surface. Transparent pixels
         * do not affect whatever pixels are already there.
         * <p>
         * This method returns immediately in all cases, even if the
         * image area to be drawn has not yet been scaled, dithered, and converted
         * for the current output device.
         * If the current output representation is not yet complete then
         * <code>drawImage</code> returns <code>false</code>. As more of
         * the image becomes available, the process that draws the image notifies
         * the specified image observer.
         * <p>
         * This method always uses the unscaled version of the image
         * to render the scaled rectangle and performs the required
         * scaling on the fly. It does not use a cached, scaled version
         * of the image for this operation. Scaling of the image from source
         * to destination is performed such that the first coordinate
         * of the source rectangle is mapped to the first coordinate of
         * the destination rectangle, and the second source coordinate is
         * mapped to the second destination coordinate. The subimage is
         * scaled and flipped as needed to preserve those mappings.
         * @param       img the specified image to be drawn
         * @param       dx1 the <i>x</i> coordinate of the first corner of the
         *                    destination rectangle.
         * @param       dy1 the <i>y</i> coordinate of the first corner of the
         *                    destination rectangle.
         * @param       dx2 the <i>x</i> coordinate of the second corner of the
         *                    destination rectangle.
         * @param       dy2 the <i>y</i> coordinate of the second corner of the
         *                    destination rectangle.
         * @param       sx1 the <i>x</i> coordinate of the first corner of the
         *                    source rectangle.
         * @param       sy1 the <i>y</i> coordinate of the first corner of the
         *                    source rectangle.
         * @param       sx2 the <i>x</i> coordinate of the second corner of the
         *                    source rectangle.
         * @param       sy2 the <i>y</i> coordinate of the second corner of the
         *                    source rectangle.
         * @param       observer object to be notified as more of the image is
         *                    scaled and converted.
         * @return   <code>true</code> if the current output representation
         *           is complete; <code>false</code> otherwise.
         * @see         java.awt.Image
         * @see         java.awt.image.ImageObserver
         * @see         java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
         * @since       JDK1.1
        public abstract boolean drawImage(Image img,
                              int dx1, int dy1, int dx2, int dy2,
                              int sx1, int sy1, int sx2, int sy2,
                              ImageObserver observer);

  • Drawing preloader line with AS?

    Hello
    I have the following AS (2) in a preloader (which works - in
    the sense that it loads the next page):
    The preloader should have a coloured line which runs from
    left to right about 0.25px thick.
    Whenever I have tried to draw the line using a pencil, it
    appears too thick, or uneven, or even goes from right to left.
    I have noticed that if I occasionally delete efforts I do not
    like, even the next page fails to load.
    What I am asking here is if it would be possible to draw the
    line in AS?
    Thanks for any useful advice.
    Steve

    Hello Devendran
    Many thanks for your post.
    So I would use something like:
    lineStyle( 1, 0xBDA0F2, 100 );
    moveTo( x1, y1 );
    lineTo( x2,y2 );
    But how would I incorporate that into my current Preloader AS
    (2)?
    Many thanks.
    Steve

  • Drawing Perpendicular Lines...

    All,
    I have a program that draws simple lines using the Line2D class. As I draw the line, I bisect it to get a point in the middle of the line. Now I have 3 points on my line.
    From here I am trying to draw a short perpendicular line originating from my bisecting point.
    I have been attempting to work from the slope formula m = (x1 - x2) / (y1 - y2), but my trig skills have gotten rusty and I can't figure out how to draw a line from an existing point and a known slope. So I have been trying to just manipulate the rise over run by taking the negative inverse (-run/rise), and adding those values to my known point. But to no avail.
    Now that I'm frustrated, I'm wondering if I'm barking up the wrong tree. Should I be using Arcs and angles to determine my perpendicular point? Or, is there an easier way to draw lines from a known point and slope?
    Thanks in advance.

    Got it.
    I was thinking about the triangle from the wrong perspective. I was making my line the adjacent side of the triangle. Once I looked at it as the hypotenuse, I realized I already had the point I was looking for.
    Was right there all along. Doh.

  • How to draw vertical lines that are visible in preview mode?

    Hi all,
    I need to draw vertical lines on a document. The lines must be same as we draw using line tool.
    I could draw the line using CreateLineSpline() method of IPathUtils.
    The problem is that these lines are not visible in preview mode. Please tell how can we make lines that are visible in preview mode.
    Please help, I'm running out of time.

    CodeSnippetRunner has the answer:
    Utils<IPathUtils>()->CreateLineSpline

  • How to draw a line on chart

    Hi all,
    I am working on a chart in Design studio on BI platform. The following screen
    shot will depict the current state of my chart-
    Now
    I need to draw lines of different lengths and colors with certain distance from
    X-axis, as shown below. (I drew those lines on a screen shot of my chart with
    the help of MS paint
    but
    I need to do this with the help of design studio) . Basically I need help to
    get the following output in design studio. So, question is HOW TO DRAW A LINE
    IN DESIGN STUDIO?
    Kindly,
    help with this.
    Please suggest me to get the output.
    Thanks and Regards.
    Rakesh.

    Hi Tammy,
    Thanks for ur reply.
    I'm using DS 1.3. and no need of dynamic changes of line on chart.
    I just now gone through with CSS, but i didnt get the solution. i think somewhere im getting stuck with CSS.
    Can u please suggest me the step by step procedure to draw a line using CSS.
    Kindly help on this.
    Thanks and Regards,
    Rakesh

  • 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

  • Using mouse to draw cicrle

    hi,
    cuold you tell me how to draw the circle by mouse on xy graph, but in this case the equation to generate cricle is not required. that mean i will change the xy graph from indicator to control status and draw on it.
    sincerely,
    Tung

    tungu123 wrote:
    first of all, i change the xy graph from "indicator" to "control" condition. after that i will draw the circles or lines on this graph.  but i do not know how to draw because xy graph is not allow to draw when it is "changed to control" condition.
    I think you are not understading the basics of a graph. Changing a graph to a control does not magically turn it into a full featured drawing program.
    Have a look at the above quoted examples. Basically you need some code to read mouse-down and mouse-move coordinates, map them to the graph scale, then generate the graph data. You can (and should) leave the graph as an indicator.
    Open the example finder an look at example "draw graph with events". Let us know how far you get. Good luck!
    Instead of a graph, you could also use a picture indicator.
    If you have a newer LabVIEW version, you can use the "plot images" feature.
    Message Edited by altenbach on 02-22-2007 11:14 PM
    LabVIEW Champion . Do more with less code and in less time .

  • How can i use this library to draw squiggly line below word for RichEditable?

    Squiggly Release Notes:
    AdobeSpellingFramework.swc
    A class that facilitates the drawing of squiggly lines below words for various text components.
    Im not using squiggly spell check egine bcause it is not supporting arabic language.
    Rest of the work i have completed, i just want to draw squiggly lines below word.
    Please help me.....Thanks

    Did you ever get an answer for this ?

  • How to Draw a line Graph using x,y Cordinates in Java ?

    Hi,
    what r the easiest way to draw a line Graph using Java Code either applet.
    can u give me code sample. or any package where we can pass some parameter so that accoring to the paramter as i know jfreeChart.function() like some method is there from toold jChart.
    Is it possible.
    Regards,
    Prabhat

    There's a number of sample applications in one of the packages of freechart, one of which should do the trick.
    If you're doing applets I suggest you look at genjar from the sourceforge site. What that does is bundle classes from a set of library jars into one jar, selecting only classes that are referenced. That should simplify the transfer problem.
    To draw graphs, typically, you create a DefaultXYDataset object, add data points and then use the appropriate ChartFactory.createXXX methods to build a chart object. Then you wrap that in a ChartPanel to display.

  • How can i use AdobeSpellingFramework.swc library to draw squiggly line below word for RichEditable?

    Written in Squiggly Release Notes:
    AdobeSpellingFramework.swc
    A class that facilitates the drawing of squiggly lines below words for various text components.
    Im not using squiggly spell check egine bcause it is not supporting arabic language.
    Rest of the work i have completed, i just want to draw squiggly lines below word.
    Please help me.....Thanks

    Did you ever get an answer for this ?

  • Drawing a curved line using the pen tool, dragging the text cursor over the line but will only give me a small area to write in, in-between a circle and a circle with a cross in?

    Drawing a curved line using the pen tool, dragging the text cursor over the line but will only give me a small area to write in, in-between a circle and a circle with a cross in?

    If you change your tool to the "Direct Selection Tool" (A) then you should be able to adjust the area for you to type in...

Maybe you are looking for

  • How to synchronize with Oracle 11 g

    Hi @ all, since a longer time I try to synchronize a Oracle Database Lite with Oracle 11 g over Mobile Server. But I still hadn't any success. I wanna use C# 3.5 and ADO.NET. Oracle Lite documentation is very bad, did not helped me. I cannot understa

  • Error creating iTunes account in Win 7 PC!

    Hi, Today I tried create iTunes account in my windows 7 pc.  I have apple ID. But don't have iTunes account to download apps. Check the screenshots. After logging in I'm seeing the following error.  It is telling "We could not complete your iTunes St

  • Inheritance for webservice parameters

    Folks, please pardon if this topic has been covered before, but my search has not found much on this specifically. I am working on webservices using weblogic 9.1. Starting with an annotated Java bean, using jwsc/jws tasks to generate EJB, etc. All th

  • Session making triouble while downloading files successively

    hi, i m hving some problems with file downloading.... my code that saves bytes array into the session is as follows byte[] bytes = proposalService.getDownload(fileName); // a method that returns bytes array             Object bt = request.getSession(

  • Additional uncaught exception thrown while handling exception.

    Hello all! I am *trying* to surf around the internet and do a little online shopping. I keep getting this error though and it is really bugging me/ruining my night. I am about ready to through my computer at a wall. Here is the error: Additional unca