Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: change background color on mouse over

I've implemented a simple mouse listener where the background color changes whenever the mouse enters the component (a JPanel), and it reverts back whenever the mouse leaves. This has some problems:

  • Sometimes the mouse moves so quick that the mouseExit event is not fired
  • If my component has childs, when the mouse moves to the childs it triggers the mouseExit
  • If I move the mouse over to the childs quickly, the mouseEnter event is not fired

I'm guessing this is an easy one for Swing veterans. Any suggestions on how to fix this? I'd love not to use timers and such...

like image 842
Miguel Ping Avatar asked Dec 29 '22 08:12

Miguel Ping


2 Answers

If I move the mouse over to the childs quickly, the mouseEnter event is not fired

I've never seen this to happen, but if it is an issue then you can handle mouseMoved instead to reset the background.

If my component has childs, when the mouse moves to the childs it triggers the mouseExit

Use the following test and the code will only be executed when you leave the components bounds:

public void mouseExited(MouseEvent e) 
{
    if (! getVisibleRect().contains(e.getPoint()) )
    {
        setBackground(...);
    }
}
like image 64
camickr Avatar answered Jan 12 '23 04:01

camickr


There are a number of solutions:

  • Add mouse listeners to the child components. Also container listeners, to add and remove listeners as components are added and removed. Unfortunately adding mouse listeners upset bubbling up of mouse events (hideous design).
  • Add a glass pane over the top. This is mighty ugly, and forwarding of events always causes problems.
  • Add an AWTEventListener to the default Toolkit and filter through for the events you are interested in. This unfortunately requires a security permission.
  • Push a custom EventQueue and filter events. This requires a security permission, put applets and WebStart/JNLP applications get that permission anyway.
like image 39
Tom Hawtin - tackline Avatar answered Jan 12 '23 04:01

Tom Hawtin - tackline