Mouse Motion Issue

Hi,
I have the following code:
     class MouseMotionHandler extends MouseMotionAdapter {
          public void mouseMoved(MouseEvent m) {
               int x  = m.getX();
               int y  = m.getY();
               int or = mapx[y*800+x];
               country = INDEX.getCountry(new Colour(or));
               if(country != null) {
                    //do something
     }An object country is returned depending on the position of the mouse over an image, which is represented by the array mapx. The if(country != null) statement works fine for preventing an exception being thrown if the mouse is within parts of the image which do not return an object. At the moment though, exceptions are thrown every time the mouse leaves the image area(i.e outside of the array which holds the colour of the underlying pixels). How could i modify it so that this would no longer happen? One way i thought of would be this:
     class MouseMotionHandler extends MouseMotionAdapter {
          public void mouseMoved(MouseEvent m) {
               int x  = m.getX();
               int y  = m.getY();
               if((x (greater than) 10 && x < 810) && (y (greater than)  10 && y < 410)) {
                    int or = mapx[y*800+x];
                    country = INDEX.getCountry(new Colour(or));
                    if(country != null) {
                         //do something
     }This is ok and does work but i was wondering if anyone can think of a better way in dealing with this problem.
Many thanks
Cath

try this code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame
     final String filename = "duke.gif";     // This is the image to be loaded
     final int columns   = 10;                    // This is the number of image columns
     final int rows  = 10;                         // This is the number of image rows
     // Note the number of columns and rows define the resolution of your mouse
     // listener... as much more cells you add to the container much more precise
     // will be the mouse listening...
     Test()
          getContentPane().setLayout(new BorderLayout());
          Image map = (new ImageIcon(filename)).getImage();
          getContentPane().add(new ImageMap(map, 10, 10), BorderLayout.CENTER);
          // The bellow line may be changed to a more suitable dimension
          setSize(300, 300);
          setVisible(true);
     static public void main(String[] args)
          new Test();
class ImageMap extends Container
     Image map = null;
     ImageMap(Image map, int width, int height)
          this.map = map;
          setLayout(new GridLayout(width, height));
          for(int i=0; i<width; i++)
               for(int j=0; j<height; j++)
                    add(new TransparentBlock("block " + i + "." + j));
     public void paint(Graphics g)
          if(map != null)
               g.drawImage(map, 0, 0, getWidth(), getHeight(), Color.white, this);
          // Note the components are not painted (transparent effect)
          // but it still active and listen the mouse events... here it is the trick
class TransparentBlock extends JComponent implements MouseListener
     public final String name;
     TransparentBlock(String name)
          this.name = name;
          addMouseListener(this);
     // Here you should process the events.. remember: each component has it own
     // position at the main frame..
     public void mouseClicked(MouseEvent e) {System.out.println("mouse clicked at the " + name);}
     public void mouseEntered(MouseEvent e) {}
     public void mouseExited(MouseEvent e) {}
     public void mousePressed(MouseEvent e) {}
     public void mouseReleased(MouseEvent e){}

Similar Messages

  • 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

  • Mouse panning issues in Flipview

    Hi,
    I have a problem in mouse panning issues in WinJS Flipview control.
    Here is my sample:
    https://skydrive.live.com/redir?resid=533F417A2E04AEC4!1009
    My problem is: I can zoom images in flipview and panning, zooming or scrolling them via finger touch.
    So, is there a simple way to enable mouse panning, scrolling?
    I think it is useless to zoom if the user cannot drag image by mouse if there is no touch device.
    Thanks so much.
    Nick

    I think adding MSGesture is a fine idea. What you're experiencing here is just a difference in the native workings of touch and mouse, so you have to manually compensate for these differences.
    Because panning and pinch/zoom in touch mode give you behaviors that are not directly translatable to mouse actions, the mouse does not interpret similar actions unless you ask it do.
    Panning with a finger is the most natural thing to expect for touchmode, but it does not directly translate into click and drag, and for that reason, mouse does not pan.  However, you can just add the event so that you get the same behavior.  It's
    extra work, but you have to take into account that not all developers want the same behavior.  For example, I expect that someone will say "I don't want to pan when I touch the screen, I want to draw a line, like I can with a mouse.  How do
    I disable this behavior?"
    I hope this clears things up for you.
    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.
    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined
    objects and unknown namespaces.

  • Mouse clicking issues

    For the last 2 weeks or so I all of a sudden have mouse clicking issues on a 2009 iMac. The mouse (I have tried 3 different ones from apple and Logitech) seem to be able to open files etc. on a click. I have to click repeatedly to get it done. When I run the disc utility it mostly goes away. Now, I run the disc repair every morning to make it go away. Annoying. I have seen other people having similar issues - it sounds like a OS issue????

    This same scenario has happened to me sporadically over the past few months and seems to be increasing. I have the Logitech Cordless Optical Mouse for Notebooks. Got it 3 years ago for use with my G4 PowerBook (1.5 GHz, 2 GB RAM, OS 10.4.8). First I thought it was the batteries, but then realized that if I'd just wait a few minutes the problem would usually go away. Nothing new electrical on my desk that would cause it. Gets really annoying. The mouse becomes sluggish and the clicks are non responsive (a right click will open a sub-menu window, but then no other clicks work. Trying to move the mouse around on the screen gives spotty results - stops and starts - as if I'm moving it on a reflective surface. After multiple clicks the window goes away. I can disconnect the USB transmitter and have complete control with the mousepad.
    Sometimes the problem won't occur all day long. Other times it comes and goes multiple times during an hour. A restart will usually get it out of that overly annoying loop.
    I bought a new Logitech Mouse a few days ago, thinking mine was wearing out, but the same thing happened within minutes.
    I can only think there's some conflict with an OSX update. VERY frustrating. I don't want to go back to a wired mouse.
    So I, too, am eager for a solution.
    Thanks,
    -Scott
    PowerBook G4, 15 in., 1.5 GHz   Mac OS X (10.4.8)   2 GB RAM; 2 LaCie 250 GB FW drives; 1 LaCie 500 GB FW drive

  • Mouse Focus Issues

    hi,
    Are there any known mouse focus issues in r12 (r12.6) ?
    we have couple of users who have these problems. this isn't with all but few of them.
    thanks,
    jazz

    Jazz,
    Review the following documents, and see if it helps.
    Note: 457136.1 - On R12 Application, Randomly The Mouse Navigation Stops Working
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=457136.1
    Note: 468724.1 - Rel 12 : Mouse Cursor Is Frozen (Loss Of Focus In Applet) After Minimizing And On Restoring the Form To Normal Size
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=468724.1
    Note: 824000.1 - Unable to Use Mouse Cursor After Accessed on Folder Tools box
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=824000.1
    Regards,
    Hussein

  • 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?

  • 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

  • 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

  • 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

  • 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());
    }

  • 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.

  • 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);
    }

  • 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

  • Please fix mouse acceleration issue

    Is Apple doing anything to fix the mouse acceleration issue? Do they know and care? I found Windows 7 even XP mouse acceleration to be great. I really wish Apple can fix something so basic.

    I have adapted this advice from a post by nycruza
    "VOLUME Control Procedure"
    http://discussions.apple.com/thread.jspa?threadID=1020767&tstart=1065
    1. Obvious but indeed there are some that forget to remove the plastic covering.
    2. Go into settings and move the volume software sliders all the way to the RIGHT. These can cap the max volume allowed of various sound outputs. If you've capped the max output, then attempt to turn your earpiece up...it won't be too loud.
    3. AFTER you have done step 2 above, use the rocker switch on the left side of the phone and push the upper side of switch. (this is ringer volume)
    4. DURING A CALL, use the rocker switch on the left side of the phone and push the upper side of switch. (this is earpiece volume)
    Note that the behavior in #3 and 4 is standard to how many cell phones operate.
    IF after doing all 4 above and your earpiece or speaker is still low or muffled you probably have a defective device.

  • 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 ...),

Maybe you are looking for

  • HT3275 Time Machine says my external hard drive does not have enough

    Time Machine says my external hard drive does not have enough space for the current backup.  It needs 34 G out of a 250G hard drive.  All that is on the drive is earlier backups.  I recently added memory, which may confuse Time Machine into thinking

  • Opening Fireworks files in Photoshop

    I created some drawings in Fireworks CS4 web standard, and sent them to a friend who has a CS4 that has photoshop instead of Fireworks, as he uses it for magazine editing and not for web publishing. The drawings went out in .png format with about 10

  • Can I auto login in to the iTunes store?

    I launch iTunes manually when needed and when I open it it askes me to log in to the iTunes Store. My user name is there and I have to enter my password. Anyway to have the password there also so I don't have to enter it every time? Is there a Save P

  • "Unfortunately, Facebook has stopped." Yes, how unfortunate.

    Okay, so my phone upgraded to ICS a couple weeks ago. It's been all fine and dandy up until three days ago. All of a sudden, I get the stupid "Unfortunately, Facebook has stopped" message multiple times when I try to use the app. And Scramble with Fr

  • Creating new categories in bugseye

    Hi! I've got a problem uploading new products to my catalog. It works find when I upload products to existing categories, but when I try to upload products to new categories it fails. I have tried to create the new category before I upload, but it th