Mouse Motion Listener

How can i detect when the mose moves when the mouse is not located on the Frame?
Here is my mouse motion listener
private class EventHandler implements AWTEventListener {
          private JPanel myPanel;
          public EventHandler(JPanel thepanel){
               myPanel = thepanel;
        public void eventDispatched(AWTEvent event) {
            if (event.getID() == MouseEvent.MOUSE_MOVED) {
                 MouseEvent me = (MouseEvent)event;
                 myScreenShooter.setCaptureLocation(me.getX(), me.getY());
                myPanel.repaint();
    }and I register it with a JPanel which I extended
Toolkit.getDefaultToolkit().addAWTEventListener(new EventHandler(this), AWTEvent.MOUSE_MOTION_EVENT_MASK);But the only time the motion is detected is when the mouse is within the panel...I need to know when it is moved anywhere on the screen.
Any ideas?
Thanks

import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
public class MotionTest
    public MotionTest()
        JLabel label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        new Monitor(label);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(label);
        f.setSize(300,100);
        f.setLocation(200,200);
        f.setVisible(true);
    public static void main(String[] args)
        new MotionTest();
class Monitor
    JLabel label;
    Point lastLocation;
    boolean continueToMonitor;
    NumberFormat nf;
    public Monitor(JLabel label)
        this.label = label;
        lastLocation = new Point();
        continueToMonitor = true;
        nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(1);
        new Thread(runner).start();
    Runnable runner = new Runnable()
        public void run()
            while(continueToMonitor)
                Point p = MouseInfo.getPointerInfo().getLocation();
                double distance = p.distance(lastLocation);
                if(distance != 0)
                    Toolkit.getDefaultToolkit().beep();
                    label.setText("mouse moved " + nf.format(distance));
                    lastLocation = p;
                else
                    label.setText("mouse still");
                try
                    Thread.sleep(250);
                catch(InterruptedException ie)
                    System.err.println("interrupt: " + ie.getMessage());
}

Similar Messages

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • Confused with Mouse Motion Listener

    I'm having a hard time understanding mouse motion listener and mouse listener.
    What I know is that it's an interface and it's supposed to be overriden, but what I don't understand is how on earth does each of the methods know what the event just did.
    How does method mouseClicked know that the mouse was just clicked and not pressed?
    As you can see, well at least to me, there's not telling how given only the passed event. I was expecting something inside the method that would go like:
    event.getWhatHappend();something like that then so you can go on with the rest of the code and say that it was actually pressed or clicked.
    public void mouseClicked( MouseEvent event )
           statusBar.setText( String.format( "Clicked at [%d, %d]",
            event.getX(), event.getY() ) );
    } // end method mouseClicked
    // handle event when mouse pressed
    public void mousePressed( MouseEvent event )
          statusBar.setText( String.format( "Pressed at [%d, %d]",
          event.getX(), event.getY() ) );
    } // end method mousePressed

    How does method mouseClicked know that the mouse was just clicked and not pressed?try this example
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class Testing extends JFrame
      public Testing()
        setSize(100,75);
        setLocation(300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        JLabel lbl = new JLabel("Click me");
        lbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        p.add(lbl);
        getContentPane().add(p);
        lbl.addMouseListener(new MouseListener(){
          public void mousePressed(MouseEvent me){
            System.out.println("pressed");
          public void mouseClicked(MouseEvent me){
            System.out.println("clicked");
          public void mouseReleased(MouseEvent me){
            System.out.println("released");
          public void mouseEntered(MouseEvent me){
            System.out.println("entered");
          public void mouseExited(MouseEvent me){
            System.out.println("exited");
      public static void main(String[] args){new Testing().setVisible(true);}
    }what happens is when you add the mouseListener to the label, it is
    registered to receive mouse events. There are 5 mouse events, each with a
    different event id.
    (watch the console for these)
    move the mouse inside the label's border, and the mouseEntered event is
    sent to registered listeners of the label.
    press the mouse button, holding it down, mousePressed is sent.
    release the mouse button, mouseReleased is sent.
    if the x,y position of mousePressed is the same as that for mouseReleased
    a mouseClicked event is fired .
    (check by again holding down the mouseButton,then move the mouse
    slightly before releasing the button - no mouseClicked event)
    move the cursor outside the label, and the mouseExited event is sent.
    so, basically, 5 separate events are available to be sent - you select the one/s
    you want to handle.

  • Reg: MouseListener and Mouse Motion Listener Interfaces

    Hi,
    Good day,
    I have added the mouselistener and mouse motion listeners to JButton..... With this i am trying to draw Circle and Line use mouse... When i was drawing at a particular point the actual drawn one is not placed at that point... so where can be error be present..how to overcome it.........
    Bye

    Insufficient information to find a solution. Please go through these links and respond accordingly.
    [How to ask questions the smart way|http://catb.org/~esr/faqs/smart-questions.html]
    SSCCE
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • Mouse motion listener outside any component

    Please show me the way to detect mouse events( move, click etc) on the system level in java. I know to detect it on any component. But say I have a java frame window with a JLabel component on it. I want to see the cursor positions (x,y) even when I am moving the mouse outside any part of the frame or its components...ie, any position on the screen( taskbar, system tray area or anywhere)

    praschat wrote:
    Please show me the way to detect mouse events( move, click etc) on the system level in java. I know to detect it on any component. But say I have a java frame window with a JLabel component on it. I want to see the cursor positions (x,y) even when I am moving the mouse outside any part of the frame or its components...ie, any position on the screen( taskbar, system tray area or anywhere)You can try JInput (it's used for gamepad/controllers in Java, but it also has abstractions for Keyboard and Mouse). JInput can be used in a quasi-event-driven way.
    If you're trying to do this through an applet in a Browser or when there's strict security manager running, you can forget about it.

  • Mouse motion listener tolerance

    I am writing a screen saver program and I am wondering if i can turn down the tolerance of the mousemoved method.
    For example I want a little mouse movements not to be registered but I do want big mouse movement to be registered. Is there a way to do that?

    Let me see if I remember correctly... the mouseEvent just gives you X and Y coordinates, so you can choose to either address the movement or not depending on the distance from your last know set of points.

  • Mouse motion events

    For some reason my custom JComponent or cutom Jpanel do not detect any mouseMotion events. Does anyone know why that is?
    I have a class like the following
    public class GeometryPanel  extends JComponent implements MouseInputListenerin my main class (the frame class) I have the following
             JFrame frame = new JFrame();
         JPanel p = new MyPanel();
         JComponent geometryPanel;
         JComponent buttonPanel = new ButtonPanel(this);
         public MainWindow()
              geometryPanel = new GeometryPanel(this,600, 600);
              setupGUI();
              displayFrame();
         public void setupGUI()
               p.setBackground( Color.white );
              p.setPreferredSize(new Dimension(width, height));
              geometryPanel.setPreferredSize(new Dimension(600, 600));
              buttonPanel.setPreferredSize(new Dimension(620, 80));
               p.add( geometryPanel );
               p.add( buttonPanel );
         public void displayFrame()
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(p);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.show();
         }For some reason all of the mouse pressed events are caught, but not the motion events. They are not fired.

    Ah I got it, thank you. Forgot to add the mouse motion listener next to the mouse listner

  • Mouse Motion Problem

    I have a JFrame which I have added a MouseMotion Listener to it, it contains many JPanels with border layout manager. I want to detect a MouseMotion in the whole Frame. But I found that only the menu bar area could fire a MouseMotionEvent when the cursor moves there. There are no mouse motion event be fired when the mouse moves on other area on the Frame. What should I do to make it works? Or should I do anything to those insided JPanels ?

    Add your MouseMotionListener to the frame's glass pane. Be sure to set the glass pane visible in order to retrieve the mouse moved events. See attached sample working code.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class GlassMotion
      public static void main(String args[])
        new GlassMotionFrame();
    class GlassMotionFrame extends JFrame implements ActionListener
      JMenuBar mb = new JMenuBar();
      JMenu file = new JMenu("File");
      JMenu edit = new JMenu("Edit");
      JMenu view = new JMenu("View");
      JMenu help = new JMenu("Help");
      JSeparator separator = new JSeparator();
      JMenuItem fileOpen = new JMenuItem("Open...");
      JMenuItem fileSaveAs = new JMenuItem("Save As...");
      JMenuItem editCut = new JMenuItem("Cut");
      JMenuItem editCopy = new JMenuItem("Copy");
      JMenuItem editPaste = new JMenuItem("Paste");
      JMenuItem helpAbout = new JMenuItem("About...");
      JPanel north = new JPanel();
      JPanel south = new JPanel();
      JPanel center = new JPanel();
      JTextField jtf = new JTextField(20);
      JTextArea jta = new JTextArea(20,30);
      JScrollPane jsp = new JScrollPane(jta);
      JButton ok = new JButton("OK");
      GlassMotionFrame()
        super();
        /* Components should be added to the container's content pane */
        Container cp = getContentPane();
        Component glassPane = getGlassPane();
        glassPane.addMouseMotionListener(new MouseMotionAdapter() {
          public void mouseMoved(MouseEvent evt) {
            System.out.println("Mouse motion event!");
        glassPane.setVisible(true);
        north.add(new JLabel("Last Name:"));
        north.add(jtf);
        center.add(jsp);
        south.add(ok);
        cp.add(BorderLayout.NORTH,north);
        cp.add(BorderLayout.CENTER,center);
        cp.add(BorderLayout.SOUTH,south);
        /* Add menu items to menus */
        file.add(fileOpen);
        file.add(separator);
        file.add(fileSaveAs);
        edit.add(editCut);
        edit.add(editCopy);
        edit.add(editPaste);
        help.add(helpAbout);
        /* Add menus to menubar */
        mb.add(file);
        mb.add(edit);
        mb.add(view);
        mb.add(help);
        /* Set menubar */
        setJMenuBar(mb);
        /* Add the action listeners */
        fileOpen.addActionListener(this);
        fileSaveAs.addActionListener(this);
        editCut.addActionListener(this);
        editCopy.addActionListener(this);
        editPaste.addActionListener(this);
        helpAbout.addActionListener(this);
        /* Add the window listener */
        addWindowListener(new WindowAdapter()
          public void windowClosing(WindowEvent evt)
            dispose();
            System.exit(0);
        /* Size the frame */
        pack();
        /* Center the frame */
        Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle frameDim = getBounds();
        setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
        /* Show the frame */
        setVisible(true);
      public void actionPerformed(ActionEvent evt)
        Object obj = evt.getSource();
        if (obj == fileOpen);
        else if (obj == fileSaveAs);
        else if (obj == editCut);
        else if (obj == editCopy);
        else if (obj == editPaste);
        else if (obj == helpAbout);
    }

  • I need help adding a mouse motion listner to my game. PLEASE i need it for

    I need help adding a mouse motion listner to my game. PLEASE i need it for a grade.
    i have a basic game that shoots target how can use the motion listner so that paint objects (the aim) move with the mouse.
    i am able to shoot targets but it jus clicks to them ive been using this:
    public void mouse() {
    dotX = mouseX;
    dotY = mouseY;
    int d = Math.abs(dotX - (targetX + 60/2)) + Math.abs(dotY - (targetY + 60/2));
    if(d < 15) {
    score++;
    s1 = "" + score;
    else {
    score--;
    s1 = "" + score;
    and here's my cross hairs used for aiming
    //lines
    page.setStroke(new BasicStroke(1));
    page.setColor(Color.green);
    page.drawLine(dotX-10,dotY,dotX+10,dotY);
    page.drawLine(dotX,dotY-10,dotX,dotY+10);
    //cricle
    page.setColor(new Color(0,168,0,100));
    page.fillOval(dotX-10,dotY-10,20,20);
    please can some1 help me

    please can some1 help meNot when you triple post a question:
    http://forum.java.sun.com/thread.jspa?threadID=5244281
    http://forum.java.sun.com/thread.jspa?threadID=5244277

  • Plz Help! How to control mouse motion(use program to move/click the mouse)?

    Hi people, plz give me some help on this: I wanna control mouse motion at another program's window, eg. control mouse movement in Internet Explorer's window. For a particular pixel on the screen, I need to move the mouse onto it instantly, then click. Please note that the java program(no applet) is going to run at the background, the current active window is some other programs like IE, notepad, etc.
    Plz give me some clue about how to achieve this, thanks.
    Do I need to do this through windows API or it can be done purely in JAVA?
    Also, how to calculate the RGB color from a particular pixel on the screen?
    Thank you very much for your time, plz help :).

    The same question each day (exe) !!!
    There are many posts on this point!
    All the soft that allows the build a native executable file on Windows
    are not free!
    You can take a look at JET excelsior
    http://www.excelsior-usa.com/home.html
    Denis

  • Detect Key Press and Mouse Motion in ONE event?

    Hi
    I am trying to create a functionality where a mouse motion from left to right performs one action, and the same motion while a given key is pressed performs another action.
    How can i combine the two events? How do I unify the KeyEvent and MouseEvent, particulary when I need to capture the directional motion of the mouse together with the key press?
    many thanks for any insight

    you cannot actualy combine them into 1 event but there is an easy way around this:boolean mouseKeyPressed = false;
    public void keyPressed (KeyEvent e)
      if (e.getKeyCode () == ??) \\ or e.isCtrlDown(), e.isAltDown(), ...
        mouseKeyPressed = true;
    public void keyReleased (KeyEvent e)
      if (e.getKeyCode () == ??) \\ or !e.isCtrlDown(), !e.isAltDown(), ...
        mouseKeyPressed = false;
    public void mouseMoved (MouseEvent e)
      if (mouseKeyPressed)
        //processAction
    }hope this helps,
    greetz,
    Stijn

  • Constraining mouse motion to specific distance (width and height)

    Hi,
    I want to constrain the mouse motion over a canvas by allowing it to move through specified distance (width and height).
    How can i do this?
    What does the translatePoint() in MouseEvent do? How do i use it?
    Can someone help me with this?
    Thanks
    Niteen

    The correct way with Pixel Bender 1.0 is indeed to pass in the width and height as parameters. There are no ramifications.

  • How to deactivate mouse (motion) event coalescing (by EventQueue)?

    Hello everybody,
    I would like to know if it is possible to deactivate the event coalescing for mouse events. I refer to the following method found in "java.awt.EventQueue":
        private boolean coalesceMouseEvent(MouseEvent e) {                            
            EventQueueItem[] cache = ((Component)e.getSource()).eventCache;              
            if (cache == null) {                                                      
                return false;                                                         
            int index = eventToCacheIndex(e);                                         
            if (index != -1 && cache[index] != null) {                                
                cache[index].event = e;                                               
                return true;                                                          
            return false;                                                             
        }                                                                              As I can see, all necessary method for modifiing the EventClass class are private. I did not found any method where I can explicitely deactivate the coalescing of mouse events.
    Other "interesting" methods are:
    - java.awt.EventQueue.coalesceEvent(AWTEvent, int)
    - java.awt.Component.coalesceEvents(AWTEvent, AWTEvent)
    But unfortunately, I did not manage to deactivate it.
    For some background information: I would like to build a drawing panel for a Tablet-PC application to draw with a digitizer/pen on it. As an optimal goal, it should be as smooth as the Windows 7 handwriting panel (don't know the official name). The trivial implementation is not fast enough - drawing quickly produces too few points (round lines with edges). And I think one reason for this is, that some mouse (motion) events get coalesced/skipped while drawing - hence this request for support.
    I'm greateful for any hint you may have
    Thanks a lot!

    if (whatever) {
        // (MouseEvent e)
        e.consume()
    } else  {
        // some usefull, but not EventQeue.push()
    } you can consume Key and Mouse events
    you have to check JComponentHierarchy because each of JComponent have got implemented KeyBindings (e.g. F2 edit JTable cell ...),

  • Regarding restricting mouse motion to a specific JPanel on JFrame

    Hello Everybody,
    I need to restrict mouse motion to a specfic area on a JFrame. I have no idea how to do that.
    Any kind of help will be highly appreciate. I tried to find that on google but could not locate anything that can help me.
    Thanks in advance.

    So, if you were to be able to do that, which you can't, then how would the user close the frame, or use the menu, or click on the task bar, or whatever?

  • Does anyone know how to make the mouse motion just NORMAL?

    Hi folks. Alright I am a new but I love my Mac. The one thing I just can't get past is the feel of the way the mouse works. It is tooooo smooth. I feel like when i go slow with the motion, it covers less ground as I move, then when I speed up my motion, it feels more in time with the motion. I realize this is pretty hard to explain but does anyone know what i am talking about? Sure it is more precise but I really hate it. Help?

    David DeCristof:
    I have been looking for a solution to this for quite some time, and I want to personally thank you for using a little humility to recognize that no, Macs don't behave the same way as other (not just Windows) graphical user interfaces when it comes to the mouse pointer.
    I downloaded and purchased (well worth the funds for me) "USB Overdrive" and now I have a pointer that moves around the screen like I'm moving my hands around the screen. So natural this way. So thank you very much for mentioning those haxies or preference applets or whatever you want to call them.
    Now my Mac is 10 times better!!!
    As an old Amiga user, and then Windows user, it has been so disorienting to work around the desktop with Mac OS's non-customizable motion preferences. It often had left me asking myself just what part of the OS is "more friendly?" Sure, it's a rock solid OS, but friendly? C'mon.....Sheesh...You mean after I find a THIRD PARTY HAXIE to make it that way?
    Well, now I have nothing to complain about.
    By the way, my Speed setting is at 160 dpi, and the Accelertaion is set at 90%, in USB Overdrive. And this feels just right for me.
    Now if only I could make my pointer WHITE instead of BLACK, (yes I guess I'm racist...) and make it about four times bigger without making it look like a lego...
    Color this thread A N S W E R E D, baby!
    17" Mac Book Pro   Mac OS X (10.4.7)  

Maybe you are looking for

  • Retenção de imposto qdo total da nota acima de 5.000,01, nao retem linha

    Gostaria de ajuda, O meu cliente é uma empresa de serviços, faz os pedidos de vendas , com varios itens de linha e depois faz a nota fiscal de saida selecionando os itens que será faturado, as configurações de retençoes estar de acordo com o valor ex

  • Saft.app message - How to Get Rid of It?

    I am a new owner of a macbook and recent 'convert' from windows to mac os. I installed and tried to uninstall saft.app (dragged everything I could find with the 'saft' name on it to 'trash', however each time I go into Safari I get the message: *'saf

  • Post Installation Steps after installation of sap sol 7.1

    Dear all Can you pls share me what are the post installation steps required after the installation of Solution Manager 7.1 I know some of them as same in ECC 1 ) SICK 2) STMS 3) RZ10 - Profile parmeters 4) SGen 5) Back ground Jobs scheduling Also tel

  • XP Pro SP2 PC can't join domain

    I had a crash and restart with an XServe that was acting as OD Master and PDC for several users. Now the trust relationship has been disrupted and I can't get the PC's to rejoin the domain. When I try, the XP box gives a message that "the user name c

  • Coherence unknown user type error

    I am getting the following error while trying to set up coherence on a project {"message":"unknown user type: com.trgr.cobalt.webcontent.coherence.PortableProperties","stackTrace":"java.lang.IllegalArgumentException: unknown user type: com.trgr.cobal