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.

Results 1 to 22 of 22

Thread: How to drag the shape to move?

  1. #1
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default How to drag the shape to move?

    Hi guys
    Below code can press to draw a random polygon whenever the mouse is pressed. I also want to drag any polygon to anywhere I want, so I have add something in the methods of mousePressed, mouseReleased, mouseDragged. but got no luck.
    Does anyone know what the problem is?
    public class Octagon extends Polygon {....} and public class Main {...} sre omitted here, see my OctagonPanel class below:

    public class OctagonPanel extends JPanel
    {
        private Octagon octagon;
        private Octagon selectedOctagon = null;
        private ArrayList<Octagon> lstOctagon = new ArrayList<Octagon>();
     
        static Random generator = new Random();
        int oldx, oldy, newx, newy;
        boolean dragging = false;
     
        public OctagonPanel()
        {
          addMouseListener (new OctagonsListener());
        }
     
       public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            for(Octagon o : lstOctagon)
            {
                o.draw(g);
            }
        }
     
         private class OctagonsListener implements MouseListener, MouseMotionListener
         {
             public void mousePressed (MouseEvent e)
             {
                oldx = e.getX();
                oldy = e.getY();
     
                for(Octagon o : lstOctagon)
                {
                   if(o.contains(oldx, oldy))
                   {
                       selectedOctagon = o;
                       dragging = true;
                   }
                }
                if(selectedOctagon == null)
                {
                    int n = generator.nextInt(80);
                    int[] newx = {oldx, oldx + n, oldx + n, oldx, oldx - 2*n, oldx - 3*n, oldx - 3*n, oldx - 2*n};
                    int[] newy = {oldy, oldy + n, oldy + 2*n, oldy + 3*n, oldy + 3*n, oldy + 2*n, oldy + n, oldy};
                    octagon = new Octagon(newx, newy, 8);
     
                    lstOctagon.add(octagon);
                    repaint();
                }
              }
     
             public void mouseReleased(MouseEvent e)
             {
                 if(dragging = true)
                 {
                     repaint();
                 }
                 selectedOctagon = null;
             }
             public void mouseClicked(MouseEvent e)
             {
             }
             public void mouseMoved(MouseEvent e) {}
             public void mouseDragged(MouseEvent e)
             {
                newx = e.getX();
                newy = e.getY();
                int xtrans = newx - oldx;
                int ytrans = newy - oldy;
                selectedOctagon.translate(xtrans,ytrans);
                repaint();
     
             }
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         }
     
     }

    Thanks heaps


  2. #2
    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: How to drag the shape to move?

    Can you define what you mean by 'no luck'? At what point does it 'break' (dragging, drawing)? Add some println statements (or use a debugger) to make sure the mousePressed and mouseDragged are doing what you wish.

  3. #3
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    Hi copeg,

    I mean I want to drag the shape to the place where I release the mouse, but the shape doesn't move at all. I thnk I have specified what to do in the methods of mousePressed, mouseReleased, mouseDragged, obviously I didn't specify them correctly.

    Is there any way to poiint out the mistakes from code of mousePressed, mouseReleased, mouseDragged apart from using debug? (At moment I am not good enough to be able to use debugger to figure out things)
    Thanks heaps

  4. #4
    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: How to drag the shape to move?

    Try adding the OctagonsListener as a mouseMotionlistener to your JPanel
    addMouseMotionListener(new OctagonsListener());

  5. #5
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    Hi copeg
    Thank you for your advice, I have changed it to what you mean (in red), then it can't even draw any polygon when I press the mouse?

    Any more thought?

     public OctagonPanel()
        {
          [COLOR="red"]addMouseMotionListener[/COLOR](new OctagonsListener());
        }
    And
    private class OctagonsListener implements MouseListener,[COLOR="Red"] MouseMotionListener[/COLOR]

  6. #6
    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: How to drag the shape to move?

    Hard to tell from your post...did you add the mouseListener AND mouseMotionListener. The two are different, and must be added using the appropriate method.

    OctagonsListeners listener = new OctaginsListener();
    addMouseListener(listener);
    addMouseMotionListener(listener);

  7. #7
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    Ah, I see what you mean - shoudl add both. Now I add both, then it comes back to the first place, which is I only can press to draw a polygon, but I still can't drag to move them.

    public OctagonPanel()
    {
    addMouseListener(new OctagonsListener());
    addMouseMotionListener(new OctagonsListener());
    }
    Any more thoughts?
    Thanks heaps

  8. #8
    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: How to drag the shape to move?

    As I mentioned in a post above, add some System.out.println statements in your code. This will allow you to see what the values are, whether certain methods or control statements are entered, etc...this is one of the first rules in debugging code (the second rule, step through code using a debugger ).

  9. #9
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    How could System.out.println help it? It just simply print text out, I still don't know what is going on. As for debugger, I am hopeless on that.
    Is there other ways to tell whic part of code is wrong? I bellieve the mistake must be inside either the methods of mousePressed, mouseReleased, mouseDragged , how to manipulate these 3 confusing things to drag the shape? (I didn't even use mouseMoved, is it ok?)

  10. #10
    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: How to drag the shape to move?

    Quote Originally Posted by ice View Post
    How could System.out.println help it?
    System.out.println doesn't help it, System.out.println helps you. In this case, printing out values can let you know the coordinates of Shape (eg Octagon), whether the Shape contains method is working properly, whether any particular methods in you code are being entered, etc...in situations such as this, printing out values is invaluable.

  11. #11
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    Thanks copeg, but it didn't work out for me, I still don't know how to fix it.
    Is there any way yo point out the error inside the code?
    Thanks heaps

  12. #12
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    Hi guys, don't give up here yet, the problem is still not solved yet.


  13. #13
    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: How to drag the shape to move?

    When you say above the println statements 'didn't fix it', what do you mean? When you add the println statements, can you tell from what the command line prints if the code enter the mousePressed and/or mouseDragged functions? If so, are the conditional if statements entered under the conditions you expect?

  14. #14
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    In fact I don't know what exact I should print to analyse; then I tried to put System.out.println(xtrans + " " + ytrans);inside mousedragged method, is that right thing to print? but it print out nothing.

    Please tell me what is going on?

    public void mouseDragged(MouseEvent e)
             {
                newx = e.getX();
                newy = e.getY();
                int xtrans = newx - oldx;
                int ytrans = newy - oldy;
                selectedOctagon.translate(xtrans,ytrans);
                repaint();
                System.out.println(xtrans + " " + ytrans);
             }

    Thanks heaps

  15. #15
    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: How to drag the shape to move?

    If it prints nothing, that tells you an enormous amount of information...it tells you that line of code is never reached. Since it is in the mouseDragged statement of a MouseMotionListener, what could be the cause? If you move that prinln statement up in the mouseDragged method, does it print anything? If you move the println statement to mouseMoved method, does it print anything? Is your MouseMotionListener added to the component?

  16. #16
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    ok, after I tidied up the code to new one below, I think I have found out a big error here:
    selectedOctagon never got selected in the methods private Octagon hitTest(MouseEvent e) and public void mousePressed (MouseEvent e).
    (Because of that, mouseClicked and mouseDragged can't act properly.)
    So how to fix that part? ..Thank you so much!


    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.JPanel;
    import java.util.ArrayList;
    import java.util.Random;
     
    public class OctagonPanel extends JPanel
    {
        private Octagon octagon;
        private Octagon selectedOctagon = null;
        private ArrayList<Octagon> lstOctagon = new ArrayList<Octagon>();
        static Random generator = new Random();
        int oldx, oldy, difx, dify, newx, newy;
     
        public OctagonPanel()
        {
             addMouseListener(new OctagonsListener());
             addMouseMotionListener(new OctagonsListener());
         }
     
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g); //optional here
            for(Octagon o : lstOctagon)
            {
                o.draw(g);
            }
     
        }
     
         private class OctagonsListener implements MouseListener, MouseMotionListener
         {
            int n;
     
            private Octagon hitTest(MouseEvent e)
            {
                Octagon hitO = null;
                for (Octagon o : lstOctagon)
                {
                    if (o.contains(e.getX(), e.getY()))
                    {
                        hitO = o;
                        break;
                    }
                }
                return hitO;
            }
     
             public void mousePressed (MouseEvent e)
             {
                selectedOctagon = hitTest(e); pressedX = e.getX();pressedY = e.getY();
             }
             public void mouseClicked(MouseEvent e)
             {
                oldx = e.getX();
                oldy = e.getY();
     
                if(selectedOctagon == null)
                {
                    System.out.println(oldx);
                    n = generator.nextInt(50);
                    int[]x = {oldx, oldx + n, oldx + n, oldx, oldx - 2*n, oldx - 3*n, oldx - 3*n, oldx - 2*n};
                    int[]y = {oldy, oldy + n, oldy + 2*n, oldy + 3*n, oldy + 3*n, oldy + 2*n, oldy + n, oldy};
     
                    octagon = new Octagon(x, y, 8);
                    lstOctagon.add(octagon);
     
                    repaint();
                }
     
             }
             public void mouseReleased(MouseEvent e)
             {
                //selectedOctagon = null; 
                repaint();
             }
     
             public void mouseMoved(MouseEvent e)
             {
             }
             public void mouseDragged(MouseEvent e)
             {
                  newx = e.getX(); newy = e.getY();
                  if(selectedOctagon != null)
                  {
                      difx = newx - pressedX; dify = newy - pressedY;
                      selectedOctagon.translate(difx, dify);
                      repaint();
                }
     
             }
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         }
     
    }
    Last edited by ice; December 15th, 2010 at 03:45 AM.

  17. #17
    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: How to drag the shape to move?

    I feel the error lies in your Octagon class, so I recommend you post that code.

  18. #18
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    great, that souds promising, here is Octagon Class:
    import java.awt.*;
    import java.util.Random;
     
    public class Octagon extends Polygon
    { 
        private int[] x; 
        private int[] y; 
        private Color color;
        static Random generator = new Random();
     
        public Octagon(int[]x, int[]y, int n)
        {
            this.x = x;
            this.y = y;
            color = new Color(Math.abs(generator.nextInt())% 16777216);
        }
     
        void draw(Graphics g)
        {
            g.setColor(color);
            g.fillPolygon(x, y, 8);
        }
     
    }

  19. #19
    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: How to drag the shape to move?

    Octagon extends Polygon, so you should make use if its capability by calling the parent constructor. As is - although not explicit - the constructor of Octagon calls the parameter-less constructor of Polygon, which creates an empty polygon. So in your other code, calling contains on a point will always be false. I would recommend making use of the Polygon class and call the parent constructor using super with those points
    public Octagon(int[]x, int[]y, int n)
        {
            super(x, y, x.length);
            this.x = x;
            this.y = y;
            color = new Color(Math.abs(generator.nextInt())% 16777216);
        }
     
    ... 
     void draw(Graphics gr){//
        Graphics2D g = (Graphics2D)gr;
        g.setColor(color);
        g.fill(this);
    }
    Last edited by copeg; December 14th, 2010 at 10:14 PM.

  20. #20
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    Wow, it does have some magic! Now mouseClick part works, selectedOctagon can get selected. But something odd happened: As soon as I start to drag selectedOctagon, it moves very very quickly to somewhere else and disappears from the whole screen. (It doesn’t follow the mouse’s drag).

    I guess is that because I didn’t use translate method in mouseDrag correctly? What do you think?

    Thanks heaps

  21. #21
    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: How to drag the shape to move?

    Once again, println's will help you see the values of how much the shape is translated. Bottom line, every time the mouse is dragged the shape is dragged by the current mouse location minus the mouse pressed location (hint, reset the old values after translating in the mouse dragged)

  22. The Following User Says Thank You to copeg For This Useful Post:

    ice (December 15th, 2010)

  23. #22
    Member ice's Avatar
    Join Date
    Nov 2010
    Location
    New Zealand
    Posts
    60
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to drag the shape to move?

    oh, my god! It finally did it!
    Thank u a lot copeg!!!

Similar Threads

  1. [SOLVED] Drag and drop in MVC
    By Alice in forum Object Oriented Programming
    Replies: 9
    Last Post: December 9th, 2010, 10:16 PM
  2. Node swap (move up)
    By raphytaffy in forum What's Wrong With My Code?
    Replies: 0
    Last Post: December 2nd, 2010, 06:56 PM
  3. Replies: 1
    Last Post: October 16th, 2010, 03:32 PM
  4. How to move an image (or how to delete one)
    By User in forum AWT / Java Swing
    Replies: 3
    Last Post: December 17th, 2009, 11:25 AM
  5. how do i draw a shape with nested loops?
    By Kilowog in forum Loops & Control Statements
    Replies: 1
    Last Post: September 25th, 2009, 12:14 AM