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 3 123 LastLast
Results 1 to 25 of 75

Thread: Canvas and MouseListener...

  1. #1
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Canvas and MouseListener...

    Hi guys,

    Here is my code:
    public class drawing extends Canvas implements MouseListener, MouseMotionListener {
     
    	private int x, y;
     
    	public drawing() {
    		setBackground(Color.WHITE);
    		addMouseListener(this);
    		addMouseMotionListener(this);
    	}
     
    	public void paint(Graphics g) {
    		Graphics2D g2 = (Graphics2D) g;
    		g2.setColor(Color.BLACK);
    		g2.setStroke(new BasicStroke(1.5f));
    		g2.drawLine(x, y, x, y);
    	}
     
    	public void mouseClicked(MouseEvent e) {}
    	public void mousePressed(MouseEvent e) {
    		x = e.getX();
            y = e.getY();
            paint(this.getGraphics());
    	}
     
    	public void mouseEntered(MouseEvent e) {}
    	public void mouseExited(MouseEvent e) {}
    	public void mouseDragged(MouseEvent e) {		
    		x = e.getX();
    		y = e.getY();
    		paint(this.getGraphics());
    	}
     
    	public void mouseMoved(MouseEvent e) {}
    	public void mouseReleased(MouseEvent e) {}
    }

    I would like to draw with Pencil and the line should be continuous. But when I use this code, fastly motion mouse cause something like that:

    obrazek.jpg

    How can I resolve it?

    Thanks for your responses!


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Canvas and MouseListener...

    Class names begin with capital letters.

    Use Swing to do your painting, study this whole lesson, including the comparison of painting in AWT and painting in Swing.

    --- Update ---

    Class names begin with capital letters.

    Use Swing to do your painting, study this whole lesson, including the comparison of painting in AWT and painting in Swing.

    Comment your code.

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Canvas and MouseListener...

    The mouse motion event may not be fired for every pixel - if you want lines, then you need to draw them from the previous point to the new point.

    And to reiterate Greg's advice above, I recommend using Swing to do your custom painting (the Canvas class is a part of AWT, which is somewhat dated and more heavyweight):
    Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)

  4. #4
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    public class Drawing extends JPanel implements MouseListener, MouseMotionListener {
     
    	private int x, y;
     
    	ArrayList<Point> Points = new ArrayList<Point>();
     
    	public Drawing() {
    		setBackground(Color.WHITE);
    		addMouseListener(this);
    		addMouseMotionListener(this);
    	}
     
    	 public void paintComponent(Graphics g) {
             super.paintComponent(g);
            // g.fillRect(10,10,100,50);
            // g.drawRect(10,80,100,50);
     
    	        Color colour = GUI.getColour();
    			g.setColor(colour);
    			((Graphics2D) g).setStroke(new BasicStroke(2));
    			for(Point p : Points)
    			g.drawLine(p.x, p.y, p.x, p.y);
          }
     
    	@Override
    	public void mouseDragged(MouseEvent arg0) {
    		// TODO Auto-generated method stub
    		x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
            paintComponent(this.getGraphics());
    	}
     
    	@Override
    	public void mouseMoved(MouseEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void mouseClicked(MouseEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void mouseEntered(MouseEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void mouseExited(MouseEvent arg0) {
    		// TODO Auto-generated method stub
    		x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
            paintComponent(this.getGraphics());
    	}
     
    	@Override
    	public void mousePressed(MouseEvent arg0) {
    		// TODO Auto-generated method stub
    		x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
            paintComponent(this.getGraphics());
    	}
     
    	@Override
    	public void mouseReleased(MouseEvent arg0) {
    		// TODO Auto-generated method stub
    		x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
            paintComponent(this.getGraphics());
    	}
    }

    Ok guys, I changed Canvas to JPanel (SWING). My code does not work anymore.

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Canvas and MouseListener...

    My code does not work anymore.
    Please describe "does not work." Are you getting errors? Does the code not perform as desired? Be specific, and ask specific questions.

    You've made some positive changes. You're on the right track.

    What is GUI?

  6. #6
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    GregBrannon, it compiles, but does not draw anything.
    GUI is another class with GUI implemented. Colouring worked good with javax.awt.Canvas, so I suspect it still works.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Canvas and MouseListener...

    Well, without seeing what you're trying to run, one can't tell what needs to be fixed. However, I've taken your code, modified it a bit (mods should have comments), and and added some code of my own to make it "go". Hope this helps, but since I don't know what you needed help with, I can't be sure.
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.ArrayList;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
     
    public class TestClass2 extends JPanel implements MouseListener, MouseMotionListener {
     
        private int x, y;
     
        ArrayList<Point> Points = new ArrayList<Point>();
     
        public TestClass2()
        {
            setBackground(Color.WHITE);
            addMouseListener(this);
            addMouseMotionListener(this);
     
            // GB: set the preferred size that will be used when the frame
            // is packed
            setPreferredSize( new Dimension( 400, 400 ) );
        }
     
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
     
            // GB: uncommented this code
            g.fillRect(10,10,100,50);
            g.drawRect(10,80,100,50);
     
            // GB: changed this to a constant since GUI is not available
            Color colour = Color.RED;
            g.setColor(colour);
            ((Graphics2D) g).setStroke(new BasicStroke(2));
            for(Point p : Points)
                g.drawLine(p.x, p.y, p.x, p.y);
        }
     
        @Override
        public void mouseDragged(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseDragged() method." );
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
            paintComponent(this.getGraphics());
        }
     
        @Override
        public void mouseMoved(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseMoved() method." );
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void mouseClicked(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseClicked() method." );
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void mouseEntered(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseEntered() method." );
            // TODO Auto-generated method stub
     
            repaint();
        }
     
        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
     
            // GB: these calls aren't necessary
            // paintComponent(this.getGraphics());
     
            repaint();
        }
     
        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
     
            // GB: these calls aren't necessary
            // paintComponent(this.getGraphics());
     
            repaint();
        }
     
        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point());
     
            // GB: these calls aren't necessary, use repaint() if needed
            // paintComponent(this.getGraphics());
     
            repaint();
        }
     
        // added a main() method to run your code on the EDT in a JFrame
        static public void main( String[] args )
        {
            SwingUtilities.invokeLater( new Runnable()
            {
                public void run()
                {
                    // creates a frame, adds your JPanel to it and displays it
                    JFrame frame = new JFrame( "Test Window" );
                    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                    frame.add( new TestClass2() );
                    frame.pack();
                    frame.setVisible( true );
                }
            });
        }
    }

  8. The Following User Says Thank You to GregBrannon For This Useful Post:

    fkmk (May 24th, 2014)

  9. #8
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    GregBrannon, thank you!
    Look, I added x, y to Points.add(new Point(x, y)); method and it draws.
    Try this code and look, what I ment.

    It draws such as in MS Paint, but fast mouse motion cause leaving empty fields. And I have a weird "refresh" while painting. How can I solve it?
    Thanks for all your responses! I am very grateful!

    Here is the code:

    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.ArrayList;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
     
    public class TestClass2 extends JPanel implements MouseListener, MouseMotionListener {
     
        private int x, y;
     
        ArrayList<Point> Points = new ArrayList<Point>();
     
        public TestClass2()
        {
            setBackground(Color.WHITE);
            addMouseListener(this);
            addMouseMotionListener(this);
     
            // GB: set the preferred size that will be used when the frame
            // is packed
            setPreferredSize( new Dimension( 400, 400 ) );
        }
     
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
     
            // GB: uncommented this code
            g.fillRect(10,10,100,50);
            g.drawRect(10,80,100,50);
     
            // GB: changed this to a constant since GUI is not available
            Color colour = Color.RED;
            g.setColor(colour);
            ((Graphics2D) g).setStroke(new BasicStroke(2));
            for(Point p : Points)
                g.drawLine(p.x, p.y, p.x, p.y);
        }
     
        @Override
        public void mouseDragged(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseDragged() method." );
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point(x, y));
            paintComponent(this.getGraphics());
        }
     
        @Override
        public void mouseMoved(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseMoved() method." );
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void mouseClicked(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseClicked() method." );
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void mouseEntered(MouseEvent arg0) {
     
            // GB: test code to check event handling
            System.out.println( "In mouseEntered() method." );
            // TODO Auto-generated method stub
     
            repaint();
        }
     
        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point(x, y));
     
            // GB: these calls aren't necessary
            // paintComponent(this.getGraphics());
     
            repaint();
        }
     
        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point(x, y));
     
            // GB: these calls aren't necessary
            // paintComponent(this.getGraphics());
     
            repaint();
        }
     
        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub
            x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point(x, y));
     
            // GB: these calls aren't necessary, use repaint() if needed
            // paintComponent(this.getGraphics());
     
            repaint();
        }
     
        // added a main() method to run your code on the EDT in a JFrame
        static public void main( String[] args )
        {
            SwingUtilities.invokeLater( new Runnable()
            {
                public void run()
                {
                    // creates a frame, adds your JPanel to it and displays it
                    JFrame frame = new JFrame( "Test Window" );
                    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                    frame.add( new TestClass2() );
                    frame.pack();
                    frame.setVisible( true );
                }
            });
        }
    }

  10. #9
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Canvas and MouseListener...

    You should never call
    paintComponent(this.getGraphics());
    manually. This method is supposed to be called from the renderer of swing. Instead of calling this method yourself simply call repaint(); in your mouseDragged method.
    If you call repaint you signal to the renderer that your component needs to be painted again. This will be done in the next rendering cycle.

  11. The Following User Says Thank You to Cornix For This Useful Post:

    fkmk (May 24th, 2014)

  12. #10
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Cornix, thank you! "Refreshes" disappeared. But empty fields are still there while fast painting.

  13. #11
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Canvas and MouseListener...

    I dont really know what you mean by that, maybe you can show a screenshot of this behavior?

  14. #12
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Cornix,
    obrazek.jpg

  15. #13
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Canvas and MouseListener...

    Well, look at your own code:
            for(Point p : Points)
                g.drawLine(p.x, p.y, p.x, p.y);
    What do you think those lines look like?
    You draw a line from each point to itself. This means that you are practically drawing points.
    You have to always connect 2 points to each other.
    1 -> 2
    2 -> 3
    3 -> 4
    ...

  16. The Following User Says Thank You to Cornix For This Useful Post:

    fkmk (May 24th, 2014)

  17. #14
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Cornix,
    for(int i=0; Points.contains(i); ++i)
    g.drawLine(Points.get(i).x, Points.get(i).y, Points.get(i+1).x, Points.get(i+1).y);

    I added this code, it compiles without errors and warnings, but it does not draw anything. :/

  18. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Canvas and MouseListener...

    Is this:
    Points.contains(i)
    ever true?
    What is the purpose of that test?
    If you don't understand my answer, don't ignore it, ask a question.

  19. #16
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Norm, yes, after mouse motion I add a new Point to ArrayList. So it should be true for these objects.

  20. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Canvas and MouseListener...

    it should be true
    Please explain how it will be true. Why will Points contain the value of i?
    If you don't understand my answer, don't ignore it, ask a question.

  21. #18
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Quote Originally Posted by Norm View Post
    Please explain how it will be true. Why will Points contain the value of i?
    It should contain 'new Point(x, y)' objects, which I have added e.g in this method:
    public void mousePressed(MouseEvent arg0) {
    		// TODO Auto-generated method stub
    		x = arg0.getX();
            y = arg0.getY();
            Points.add(new Point(x, y));
            //paintComponent(this.getGraphics());
            repaint();
    }

  22. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Canvas and MouseListener...

    It should contain 'new Point(x, y)' objects
    Yes. But the int i is NOT a Point object. There shouldn't be the value i in the list: contains(i) can never be true.

    What do you want the for loop to do? Should it look at ALL of the Point objects in the list?


    Following for other Mods:
    This seems like a hole in the java compiler's testing. Why isn't contains(i) flagged as an error?
    The statement: add(i) will be flagged as an error, but it is symmetrical with contains(i).
    Why be able to test if a list contains something if that something can not be added?
    If you don't understand my answer, don't ignore it, ask a question.

  23. #20
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Norm, exactly. It should look at all of the points.

    And thanks for you all pieces of advice.

  24. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Canvas and MouseListener...

    It should look at all of the points
    Do you understand how to write the termination condition of a for statement? Take a look at the tutorial:
    The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
    If you don't understand my answer, don't ignore it, ask a question.

  25. #22
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Canvas and MouseListener...

    Quote Originally Posted by Norm View Post
    Following for other Mods:
    This seems like a hole in the java compiler's testing. Why isn't contains(i) flagged as an error?
    The statement: add(i) will be flagged as an error, but it is symmetrical with contains(i).
    Why be able to test if a list contains something if that something can not be added?
    The add method of collections takes a generic typed parameter. The contains method takes Object.
    I assume that the OP uses a compiler that automatically casts int i to Integer.valueOf(i). The resulting Integer is an Object and can be used as an argument to contains, but not to add since the add method would require a Point object in this specific case.

  26. #23
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Thank you guys for all your tips! I have solved the problem.
    The correct code for a loop is:
    for(int i=0; i<Points.size()-1; i++) {
    				Point p1, p2 = null;
    				p1 = Points.get(i);
    				p2 = Points.get(i+1);
    				g.drawLine(p1.x, p1.y, p2.x, p2.y);
    			}

    Thanks for all your responses! I am very grateful!

  27. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Canvas and MouseListener...

    Another way to code it:
          Point startPt = points.get(0);    // start at first point
          for(int i=1; i < points.size(); i++) { // first end at second pt
             Point endPt = points.get(i);   //  get end point
             // draw from startPt to endPt
             startPt = endPt;              // set new starting point
          }   // end for through points
    This gets each point just once from the list.
    If you don't understand my answer, don't ignore it, ask a question.

  28. #25
    Member
    Join Date
    Mar 2014
    Posts
    49
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Canvas and MouseListener...

    Guys, another problem has occured...

    It draws excatly, how I wanted, but now when I stop drawing, and start in another place, last point from 'previous' point connects with new Point from 'new drawing'.
    I just want to draw with pencil, such how it is in MS Paint.

    Thank you guys for all!

Page 1 of 3 123 LastLast

Similar Threads

  1. MouseListener
    By Karthik Prabhu in forum AWT / Java Swing
    Replies: 5
    Last Post: June 30th, 2012, 02:18 AM
  2. [SOLVED] Image on JPanel ---> Canvas
    By justyStepi in forum AWT / Java Swing
    Replies: 19
    Last Post: May 8th, 2012, 07:20 PM
  3. Need help to save Canvas content to a file
    By piulitza in forum AWT / Java Swing
    Replies: 3
    Last Post: December 27th, 2011, 11:20 AM
  4. MouseListener
    By _lithium_ in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 18th, 2011, 11:43 AM
  5. make textbox in canvas
    By mahdi in forum Java ME (Mobile Edition)
    Replies: 2
    Last Post: October 6th, 2009, 07:10 AM