Search code examples
javaswingawtmouseeventmouseenter

Java MouseEvents not working


This may be a stupid question, but I have to ask!

I have the following code snippets that are supposed to run their corresponding methods when the user interacts with objects. For some reason, "foo" is never printed, but "bar" is.

myJSpinner1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
    System.out.println("foo"); //"foo" is not printed
  }
});

myJSpinner2.addChangeListener(new java.awt.event.ChangeListener() {
    public void stateChanged(java.awt.event.ChangeEvent evt) {
    System.out.println("bar"); //"bar" is printed
  }
});

I get no exceptions or stack trace. What am I missing in the MouseListener one? Thanks in advance.

EDIT: MouseEntered works perfectly on a JCheckBox implemented in exactly the same way!


Solution

  • JSpinner is a composite component consisting of a text field and 2 buttons. It's possible to add mouse listeners to all of those by iterating over the results of getComponents() and adding a listener to each.

    However, in my experience, when something takes that much work, you're probably going about it the wrong way.

    Why do you need the mouse-entered information for a JSpinner?
    What do you want to do with this event?

    Update: If you're looking to supply information about all of the controls in your panel, you may want to look at using a glasspane to detect the component under the mouse.

    A Well-behaved Glasspane by Alexander Potochkin is a good place to start.