Results 1 to 5 of 5
  1. #1
    Join Date
    Apr 2010
    Posts
    13
    Rep Power
    0

    Default [NOT SOLVED] Forcing the mouse to stay quiet

    Hello, everbody.

    In the process of learning more about events and listeners I decided to modify the program from my previous post (a very simple application that draws a circle on the center of the window, then deletes and draws it again when the user clicks a mouse button) so that it draws the circle anywhere within the window, and checks if the user clicked over the circle as opposed to the original code, in which it didn't matter where the user clicked. I also want the user to have to track the circle, so I need the mouse cursor to be positioned in a certain point (in this case, the center of the screen) and stay there until the circle is painted, and return there immediately when the circle is deleted so that it can start over again in the same conditions. And this is the part that doesn't work.

    Here is the SSCCE:

    Java Code:
    import java.awt.AWTException;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.Robot;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class Example extends JPanel {
    
        private static final long serialVersionUID = 0L;
        JButton startButton;
        Timer drawTimer;
        Robot R2D2;
        Random rand;
        private boolean testStarted = false;
        private boolean stimPresent = false;
        private boolean draw = false;
        private int currentIteration = 0;
        private int lapse = 0;
        private int xCoord = 0;
        private int yCoord = 0;  
        
        public class ClickMoveListener extends MouseAdapter {
            @Override
            public void mousePressed(MouseEvent arg0) {     
                try {
                    Point clickPoint = new Point(MouseInfo.getPointerInfo().getLocation());
                    R2D2 = new Robot();
                    if (testStarted) {
                        if (!stimPresent) {                        
                            drawTimer.stop();
                        } else {
                            Color c = R2D2.getPixelColor(clickPoint.x, clickPoint.y);
                            if (!c.equals(Color.BLACK)) {
                                drawTimer.stop();
                            }
                        }
                        R2D2.mouseMove((getWidth()/2),(getHeight()/2));                    
                        draw = false;
                        repaint();
                        if (currentIteration < 5) {
                            currentIteration++;
                            lapse = new Random().nextInt(4000);
                            drawTimer.setInitialDelay(lapse);
                            drawTimer.start();
                        }
                    }
                } catch (AWTException ex) {
                }
            }
            
            @Override
            public void mouseMoved(MouseEvent arg0) {       
                if (testStarted) {
                    try {
                        R2D2 = new Robot();
                        if (!stimPresent) {
                            R2D2.mouseMove((getWidth()/2),(getHeight()/2));
                        }
                    } catch (AWTException ex) {
                    }
                }   
            }
        }
         
        public class DrawTimerListener implements ActionListener {
            public void actionPerformed(ActionEvent arg0) {
                draw = true;
                repaint();
            }
        }  
        
        public class StartButtonActionListener implements ActionListener {
            public void actionPerformed(ActionEvent arg0) {
                testStarted = true;
                startButton.setEnabled(false);
                currentIteration = 1;
                drawTimer.setInitialDelay(lapse);
                drawTimer.start(); //wait and draw
    	    try {
    	      R2D2 = new Robot();
    	      R2D2.mouseMove(getWidth()/2, getHeight()/2);
    	    } catch (AWTException ex) {
                }
            }
        }
       
        public static void main(String[] args) {
            try {           
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (draw) {
                g.setColor(Color.BLACK);
                rand = new Random();
                xCoord = rand.nextInt(getWidth());
                yCoord = rand.nextInt(getHeight());
                g.fillOval(xCoord-20,yCoord-20,20,20);
                stimPresent = true;
            }else {
                stimPresent = false;
            }
        }
        
        private static void createAndShowGUI() {
            JDialog frame = new JDialog();
            frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            frame.setTitle("Example");
            frame.setModal(true);
            JComponent newContentPane = new Example();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.setPreferredSize(new Dimension(640, 480));
            frame.setLocationRelativeTo(null);
            frame.pack();        
            frame.setVisible(true);
        }
    
        public Example() {
            super(new BorderLayout());
            drawTimer = new Timer(lapse,new DrawTimerListener());
            drawTimer.setInitialDelay(lapse);
            drawTimer.setRepeats(false);
            JPanel buttonPanel = new JPanel();
            startButton = new JButton("Start");
            startButton.addActionListener(new StartButtonActionListener());
            buttonPanel.add(startButton);
            add(buttonPanel,BorderLayout.PAGE_END);
            addMouseListener(new ClickMoveListener());
        }      
    }
    As you can see, what I have is a JPanel and a JButton inside a JFrame, and when the JButton is pressed a circle is drawn anywhere in the JPanel. To deal with the restriction of starting with the cursor in the center of the window and returning it there when the user clicks the mouse button, I've made use of the Robot class and its mouseMove() method in the mouseClicked() and mouseMoved() methods of my MouseAdapter.

    The expected behaviour is that once the JButton is pressed the cursor should move to the center of the JFrame and stay there until the circle is painted, and repeat the same sequence (forcing mouse position and preventing it from moving, then drawing the circle, then allowing the mouse to move once the circle is painted) upon clicking the mouse button. The actual behaviour is that mouse movement is not prevented, and the mouse position is only forced (to the parent window's center, apparently, instead of the actual window's center) upon mouse click but not on mouse movement when the circle hasn't been painted.

    So it's obvious I'm doing something wrong, but I don't know where I made the mistake (or probably mistakes) that prevents this from working as expected. Any ideas?
    Last edited by ProspectiveDeveloper; 05-02-2010 at 02:13 PM.

  2. #2
    Join Date
    Apr 2010
    Posts
    13
    Rep Power
    0

    Default

    I seem to have located the source of the problem: my program doesn't even enter the mouseMoved() method when the mouse is moved. And this happens because MouseAdapter doesn't have that method. Protip: I should check the documentation before I ask. Solution: use MouseMotionAdapter.

    The problem of disabling mouse movement still persists.
    Last edited by ProspectiveDeveloper; 05-02-2010 at 02:11 PM.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by ProspectiveDeveloper View Post
    I seem to have located the source of the problem: my program doesn't even enter the mouseMoved() method when the mouse is moved. And this happens because MouseAdapter doesn't have that method.
    Are you 100% sure? Have you looked at the MouseAdapter API? Have you re-looked? Did your code cause a compiler error by having @Override above your attempted override of MouseAdapter's mouseMoved method?

  4. #4
    Join Date
    Apr 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Are you 100% sure? Have you looked at the MouseAdapter API? Have you re-looked? Did your code cause a compiler error by having @Override above your attempted override of MouseAdapter's mouseMoved method?
    My code did not cause a compiler error. I have looked and re... Oh, please someone slap me. I was looking at the 1.4.2 documentation. MouseAdapter from 1.6 does implement it, which means that the cause for the code in my first post in this thread not entering the mouseMoved method probably is that I need to add the Listener both as a MouseListener and as a MouseMotionListener (I was only adding it as a MouseListener).

    EDIT: Confirmed. The error was exactly that. Now I just need to find why the mouse is forced to be on the center of the terminal from which I run the application, instead of the center of the JFrame.

    Also, it seems I can't unmark the thread as solved or mark it as unsolved.
    Last edited by ProspectiveDeveloper; 05-02-2010 at 06:00 PM.

  5. #5
    Join Date
    Apr 2010
    Posts
    13
    Rep Power
    0

    Default

    Quote Originally Posted by ProspectiveDeveloper View Post
    Now I just need to find why the mouse is forced to be on the center of the terminal from which I run the application, instead of the center of the JFrame.
    And that was also solved, I needed to get the position of the frame on the screen, otherwise the mouseMove method of the Robot class moved the mouse cursor to the wrong place since apparently it uses coordinates relative to the screen, not the window. So I replaced all instances of mouseMove with this, and now the mouse cursor stays in the center of the JFrame like I wanted:


    Point location = getLocationOnScreen();
    R2D2.mouseMove(location.x+(getWidth()/2),location.y+(getHeight()/2));

Similar Threads

  1. Replies: 2
    Last Post: 03-30-2010, 06:36 PM
  2. Mouse Listener for mouse floating over object?
    By Krooger in forum AWT / Swing
    Replies: 1
    Last Post: 11-18-2009, 05:34 AM
  3. Forcing a thread to stop
    By sukatoa in forum Threads and Synchronization
    Replies: 7
    Last Post: 07-17-2009, 07:41 AM
  4. drawing with mouse
    By aveek in forum Java 2D
    Replies: 1
    Last Post: 06-27-2009, 02:38 PM
  5. Mouse over JButton
    By sandor in forum AWT / Swing
    Replies: 1
    Last Post: 05-17-2007, 10:15 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •