user3058906
user3058906

Reputation: 11

stop mouseEntered execution when mouse exits the element JFrame

my app plays different sounds when entering the area of different buttons. when the mouse exits the area of a button, i want all sounds to stop. i start the sounds in the mouseEntered method, and stop them in the mouseExited method:

    @Override
public void mouseEntered(MouseEvent mouse) { 
    allForms.playSounds(mouse);
}

@Override
public void mouseExited(MouseEvent mouse) {
     allForms.stopSounds(mouse);
}

the problem is the mouseEntered method won't stop it's execution in the middle to start executing mouseExited.

is there a way to solve this problem?

Upvotes: 0

Views: 116

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

You appear to be calling a long-running bit of code on the Swing event thread, tying up the thread. A solution is to call the playSounds in a background thread which should free up the Swing thread so that it responds to you and will hopefully allow you to call stopSounds. A SwingWorker can help you create a background thread and allow its code interact with swing in a thread-safe manner.

As an aside, another way to trigger your code would be to listen to your JButton's ButtonModel for roll over events.


Edit
You state in comment:

is it possible to use SwingWorker without having to extend the class? my class already extends JFrame.

  • Your SwingWorker could be in its own class, or could be an anonymous inner class if it's small enough. If separate, it would be part of your "control" code, assuming that you've factored your code into an M-V-C pattern (or Model-View-Control).
  • For what it's worth, I rarely if ever create GUI code that extends a top level window such as a JFrame, and avoiding this has saved me from problems and frustration.

Upvotes: 2

Related Questions