Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 4 123 ... LastLast
Results 1 to 25 of 86

Thread: drawLine problem, lines not connected

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default drawLine problem, lines not connected

    So I'm having an issue with drawLine; my program tracks the mouses movement when moving and when dragged and displays it on the screen, I also want a little drawing function as to have a visual representation of what they did. I used drawLine and for some reason the lines aren't really connected, the faster the mouse moves, the more dotted and broken the line is!

    Heres MouseMotionEventDemo.java
     
    package events;
     
    /*
     * MouseMotionEventDemo.java
     *
     */
     
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
     
     
    public class MouseMotionEventDemo extends JPanel
            implements MouseMotionListener {
        BlankArea blankArea;
        JTextArea textArea;
        int lastX=0, lastY=0;
        static final String NEWLINE = System.getProperty("line.separator");
     
        public static void main(String[] args) {
            /* Use an appropriate Look and Feel */
            try {
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            } catch (UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
     
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            /* Turn off metal's use of bold fonts */
            UIManager.put("swing.boldMetal", Boolean.FALSE);
     
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("MouseMotionEventDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            JComponent newContentPane = new MouseMotionEventDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
     
     
        }
     
        public MouseMotionEventDemo() {
            super(new GridLayout(0,1));
            blankArea = new BlankArea(Color.WHITE);
            add(blankArea);
     
            textArea = new JTextArea();
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setPreferredSize(new Dimension(200, 75));
     
            add(scrollPane);
     
            //Register for mouse events on blankArea and panel.
            blankArea.addMouseMotionListener(this);
            addMouseMotionListener(this);
     
     
            setPreferredSize(new Dimension(450, 450));
            /*setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); */
     
        }
     
        void eventOutput(String eventDescription, MouseEvent e) {
            textArea.append(eventDescription
                    + " (" + e.getX() + "," + e.getY() + ")"
                    + " detected on "
                    + e.getComponent().getClass().getName()
                    + NEWLINE);
            lastX = e.getX();
            lastY = e.getY();
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
     
       public void mouseMoved(MouseEvent e) {
            eventOutput("Mouse moved", e);
        }
     
        @Override
       public boolean mouseDown(Event e, int x, int y){
           return(record(x,y));
                   }
     
        @Override
       public boolean mouseEnter(Event e, int x, int y) {
            return(record(x, y));
            }
     
       public void mouseDragged(MouseEvent e) {
            eventOutput("Mouse dragged", e);
            Graphics g = getGraphics();
            g.drawLine(lastX, lastY, e.getX(), e.getY());
            record(e.getX(), e.getY());
        }
     
        @Override
       public void paintComponent(Graphics g) {
                super.paintComponent(g);
              /*  g.drawLine(lastX, lastY, newX, newY);
                repaint(lastX, lastY, newX, newY); */
            }
       protected boolean record(int x, int y){
            lastX = x;
            lastY = y;
            return(true);
        }
    }


    BlankArea.java is this
    /*
     * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     *   - Redistributions of source code must retain the above copyright
     *     notice, this list of conditions and the following disclaimer.
     *
     *   - Redistributions in binary form must reproduce the above copyright
     *     notice, this list of conditions and the following disclaimer in the
     *     documentation and/or other materials provided with the distribution.
     *
     *   - Neither the name of Oracle or the names of its
     *     contributors may be used to endorse or promote products derived
     *     from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
     * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */ 
     
    package events;
     
    /*
     * BlankArea.java is used by:
     *    MouseEventDemo.java.
     *    MouseMotionEventDemo.java
     */
     
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.*;
     
     
     
    public class BlankArea extends JLabel {
        Dimension minSize = new Dimension(100, 50);
     
        public BlankArea(Color color) {
            setBackground(color);
            setOpaque(false);
            setBorder(BorderFactory.createLineBorder(Color.black));  
     
        }
     
      }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    The code should do the drawing in the paintComponent() method. The other methods should define where the lines are to be drawn and save that data in a collection and then call repaint(). The paintComponent() method will then get the data from the collection and use it to draw the lines.

    See the link posted earlier to the tutorial's custom painting topic
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    Where should the current x and y be recorded? I can't use e.getX() in the paintcomponent since it doesn't recognize e

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    Create a collection like an ArrayList to hold the data for paintComponent() to use.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: drawLine problem, lines not connected

    See Norm's post #2:
    The other methods should define where the lines are to be drawn and save that data in a collection and then call repaint().

  6. #6
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    Now I'm just getting confused as to where to record all of the coordinates, as in, the current xy and the previous xy

  7. #7
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

     
    package events;
     
    /*
     * MouseMotionEventDemo.java
     *
     */
     
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.util.*;
     
     
    public class MouseMotionEventDemo extends JPanel
            implements MouseMotionListener {
        BlankArea blankArea;
        JTextArea textArea;
        int lastX=0, lastY=0, currX=0, currY=0;
        ArrayList al = new ArrayList();
        Object ia[] = al.toArray();
        static final String NEWLINE = System.getProperty("line.separator");
     
        public static void main(String[] args) {
            /* Use an appropriate Look and Feel */
            try {
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            } catch (UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
     
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            /* Turn off metal's use of bold fonts */
            UIManager.put("swing.boldMetal", Boolean.FALSE);
     
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("MouseMotionEventDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            JComponent newContentPane = new MouseMotionEventDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
     
     
        }
     
        public MouseMotionEventDemo() {
            super(new GridLayout(0,1));
            blankArea = new BlankArea(Color.WHITE);
            add(blankArea);
     
            textArea = new JTextArea();
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setPreferredSize(new Dimension(200, 75));
     
            add(scrollPane);
     
            //Register for mouse events on blankArea and panel.
            blankArea.addMouseMotionListener(this);
            addMouseMotionListener(this);
     
     
            setPreferredSize(new Dimension(450, 450));
            /*setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); */
     
        }
     
        void eventOutput(String eventDescription, MouseEvent e) {
            textArea.append(eventDescription
                    + " (" + e.getX() + "," + e.getY() + ")"
                    + " detected on "
                    + e.getComponent().getClass().getName()
                    + NEWLINE);
            lastX = e.getX();
            lastY = e.getY();
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
     
       public void mouseMoved(MouseEvent e) {
          currX = e.getX();
          currY = e.getY();
           eventOutput("Mouse moved", e);
           record(currX, currY);
       }
     
        @Override
       public boolean mouseDown(Event e, int x, int y){
            return(record(x,y));
            }
     
        @Override
       public boolean mouseEnter(Event e, int x, int y) {
            return(record(x, y));
            }
     
       public void mouseDragged(MouseEvent e) {
            eventOutput("Mouse dragged", e);
        }
     
        @Override
       public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawLine(lastX, lastY, currX, currY);
                record(lastX,lastY);
                repaint();
            }
       protected boolean record(int x, int y){
            lastX = x;
            lastY = y;
            return(true);
        }
    }

    All it's doing is keeping the first point concrete and changing the current xy, so all moving the mouse does when clicked is pivot the line around a point

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    The data for the lines is not being saved properly. For each line you need to save the starting x,y and the ending x,y. You should define a class to hold the data for a line and save instances of that class in a collection.
    The paintComponent() method will go through the saved data for the lines and draw them one by one.

    paintComponent() should NOT call repaint(). Will be an infinite loop.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    But I don't want it to draw "lines" i just want it to draw where the mouse is, as it's being dragged, like you'd do in MS paint

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    What other choices of drawing methods will give you the visual that you are looking for?
    Look at the Graphics class to see what is available.
    Personally I think the connecting "lines" between mouse positions can be represented by drawing lines between each position.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    I've tried looking up things, like i said i'm REALLY new at java and am just overwhelmed with this right now.
    I just wanted a simple click, move mouse and have it paint where you move the mouse.

    package events;
     
    /*
     * MouseMotionEventDemo.java
     *
     */
     
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.util.*;
     
     
    public class MouseMotionEventDemo extends JPanel
            implements MouseMotionListener {
        BlankArea blankArea;
        JTextArea textArea;
        int lastX=0, lastY=0, currX=0, currY=0;
        ArrayList al = new ArrayList();
        Object ia[] = al.toArray();
        static final String NEWLINE = System.getProperty("line.separator");
     
        public static void main(String[] args) {
            /* Use an appropriate Look and Feel */
            try {
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            } catch (UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
     
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            /* Turn off metal's use of bold fonts */
            UIManager.put("swing.boldMetal", Boolean.FALSE);
     
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("MouseMotionEventDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            JComponent newContentPane = new MouseMotionEventDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
     
     
        }
     
        public MouseMotionEventDemo() {
            super(new GridLayout(0,1));
            blankArea = new BlankArea(Color.WHITE);
            add(blankArea);
     
            textArea = new JTextArea();
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setPreferredSize(new Dimension(200, 75));
     
            add(scrollPane);
     
            //Register for mouse events on blankArea and panel.
            blankArea.addMouseMotionListener(this);
            addMouseMotionListener(this);
     
     
            setPreferredSize(new Dimension(450, 450));
            /*setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); */
     
        }
     
        void eventOutput(String eventDescription, MouseEvent e) {
            textArea.append(eventDescription
                    + " (" + e.getX() + "," + e.getY() + ")"
                    + " detected on "
                    + e.getComponent().getClass().getName()
                    + NEWLINE);
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
     
       public void mouseMoved(MouseEvent e) {
           eventOutput("Mouse moved", e);
           currX = e.getX();
           currY = e.getY();
           record(e.getX(),e.getY());
           repaint();
       }
     
       public boolean mouseDown(Event e, int x, int y){
           return(record(x,y));
       }
     
        @Override
       public boolean mouseEnter(Event e, int x, int y) {
            return(record(x, y));
        }
     
       public void mouseDragged(MouseEvent e) {
            eventOutput("Mouse dragged", e);
            currX = e.getX();
            currY = e.getY();
            repaint();
        }
     
        @Override
       public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawLine(lastX, lastY, currX, currY);
     
       }
     
       protected boolean record(int x, int y){
            lastX = x;
            lastY = y;
            return(true);
        }
    }

    could you test this and see what works for you?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    How many lines do you want drawn?
    Enough to show where the mouse has moved
    Or just one from the click point to the current mouse position
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    Quote Originally Posted by Norm View Post
    How many lines do you want drawn?
    Enough to show where the mouse has moved
    Or just one from the click point to the current mouse position
    Enough to show where the mouse has moved, just like if you opened MS Paint and used the pencil function

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    Two ways I know to do it:
    Save the end points for each mouse move as lines and have paintComponent() draw those lines.
    Create a BufferedImage, get its graphics, draw on it and have paintComponent() draw it as an image.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    That was my original thought was that I was going to save the end points as the mouse moves, but i couldn't figure out where exactly to put the code for current xy and previous xy.

    You sort of hinted at it, but like I said I'm a newbie at Java so I have no idea where to do that stuff

  16. #16
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    you mentioned paintcomponent and I tried to throw something in there but all I ever got was one endpoint not moving, and the other just following the cursor instead of painting. I just don't know how to set everything up

    EDIT: All in all I think i just need to know how paintComponent is set up and how the function that repaints is set up

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    Your only concern with repaint() and paintComponent() is that calling repaint() causes paintComponent() to be called.

    For a simple test, add a bunch of Point objects to an array list, say in the class's constructor. In paintComponent() get the first two and draw a line between them. Then get the third and draw from it to the second point. Then get the fourth and draw a line from it to the third, etc.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    Oh wow that clears a few things up! ok I understand a bit more now.

    So I tweaked things and, if you run this code you'll see that there is just a small trail behind the cursor instead of it actually drawing the WHOLE line, it just draws from the last xy to the current, and keeps doing that without "saving" it. What do I need to move around?

    package events;
     
    /*
     * MouseMotionEventDemo.java
     *
     */
     
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.util.*;
     
     
    public class MouseMotionEventDemo extends JPanel
            implements MouseMotionListener {
        BlankArea blankArea;
        JTextArea textArea;
        int lastX=0, lastY=0, currX=0, currY=0;
        ArrayList al = new ArrayList();
        Object ia[] = al.toArray();
        static final String NEWLINE = System.getProperty("line.separator");
     
        public static void main(String[] args) {
            /* Use an appropriate Look and Feel */
            try {
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            } catch (UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
     
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            /* Turn off metal's use of bold fonts */
            UIManager.put("swing.boldMetal", Boolean.FALSE);
     
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("MouseMotionEventDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            JComponent newContentPane = new MouseMotionEventDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
     
     
        }
     
        public MouseMotionEventDemo() {
            super(new GridLayout(0,1));
            blankArea = new BlankArea(Color.WHITE);
            add(blankArea);
     
            textArea = new JTextArea();
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setPreferredSize(new Dimension(200, 75));
     
            add(scrollPane);
     
            //Register for mouse events on blankArea and panel.
            blankArea.addMouseMotionListener(this);
            addMouseMotionListener(this);
     
     
            setPreferredSize(new Dimension(450, 450));
            /*setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); */
     
        }
     
        void eventOutput(String eventDescription, MouseEvent e) {
            textArea.append(eventDescription
                    + " (" + e.getX() + "," + e.getY() + ")"
                    + " detected on "
                    + e.getComponent().getClass().getName()
                    + NEWLINE);
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
     
       public void mouseMoved(MouseEvent e) {
           eventOutput("Mouse moved", e);
           currX = e.getX();
           currY = e.getY();
           record(e.getX(),e.getY());
       }
     
       public boolean mouseDown(Event e, int x, int y){
           return(record(x,y));
       }
     
       public boolean mouseEnter(Event e, int x, int y) {
            return(record(x, y));
        }
     
       public void mouseDragged(MouseEvent e) {
            eventOutput("Mouse dragged", e);
            currX = e.getX();
            currY = e.getY();
            repaint();
        }
     
        @Override
       public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawLine(lastX, lastY, currX, currY);
            record(currX,currY);
       }
     
       protected boolean record(int x, int y){
            lastX = x;
            lastY = y;
            return(true);
        }
    }

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    Did you try the simple test I suggested using an ArrayList and some points?
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    Not even sure where to start with that.

    I'll just figure this out tomorrow or something, because I don't have a clue whats going wrong.

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    Which part are you having problems with?
    Define an ArrayList
    Repeat the next two steps several times
    Define a Point
    Add Point to the ArrayList
    Getting the contents of the ArrayList
    Using two Points to draw a line

    whats going wrong.
    Where was there anything going wrong? The code seems to work.
    It draws a line between the last two mouse positions.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #22
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    Yeah it draws a line between the last two mouse positions, but I want that to save on the screen.
    like i said, it's like going into Microsoft Paint and using the Pen feature. hm

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    If you want lines drawn between the old positions of the mouse, you need to save them so the paintComponent() method can use them. This has been discussed several times.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #24
    Member
    Join Date
    Sep 2012
    Posts
    65
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: drawLine problem, lines not connected

    I've never had to use arraylist before though. I made a basic whiteboard app without any frames or windows or mouse tracking or anything, and it didn't use arrayList.



    Here's my issue; go to paintComponent and comment out "super.paintComponent(g); " and tell me what you get.
    for me I am able to draw JUST like I want, but the mouse tracking text extends into the drawing screen?

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: drawLine problem, lines not connected

    That will sort of work until something covers the screen.
    Minimize and restore the window.
    Last edited by Norm; September 3rd, 2012 at 03:07 PM.
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 4 123 ... LastLast

Similar Threads

  1. help with keeping client connected to server
    By frozen java in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 19th, 2011, 02:29 PM
  2. Problem with printing out collinear lines!
    By rkrajnov in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 25th, 2011, 06:32 PM
  3. Problem with Output # of lines
    By coyboss in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 7th, 2011, 10:21 PM
  4. Why rs...still connected
    By javamula in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 30th, 2011, 04:53 PM
  5. g.drawLine doesn't draw line in for loop
    By shumpi in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 12th, 2010, 07:15 PM