Albin Wärme
Albin Wärme

Reputation: 57

Java obtain focus

So I'm working on a Piano like-program in Java. I use a method that looks like this to trigger the correct sound for each key

public void Sound(String file){

    try{
        AudioInputStream ais = AudioSystem.getAudioInputStream(getClass().getResource(file));
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(getClass().getResource(file)));
        clip.start();
    }catch(Exception e){
        e.printStackTrace();
    }

    game.setFocusable(true);//my desperate try to regain focus on click...
    game.requestFocus();

}

What happends however is that after a period of time the KeyListener totaly loses the focus and the KeyEvent will not be triggerd anymore. If anyone knows how I can obtain focus on the KeyListener in the frame I would more then likely hear out on what you have to say.

What I have tried:

  1. upon trigger set the panel to focus-able again

  2. Made sure so that the program still runs in the background and indeed it is the panel losing focus.

  3. Small other adjustments

Upvotes: 0

Views: 96

Answers (2)

ionut stanca
ionut stanca

Reputation: 1

You can force the focus adding the event with high priority queue. I used this in application that scan barcodes and they have a very high speed in sending key events, and i need to use this in order to lose focus and gaing the focus in other fields.

You can do something like this, replace:

game.setFocusable(true);//my desperate try to regain focus on click...
    game.requestFocus();

with

      SunToolkit.flushPendingEvents();
      FocusEvent fl = new CausedFocusEvent(game, FocusEvent.FOCUS_GAINED, false, null,
                        CausedFocusEvent.Cause.TRAVERSAL);
       SunToolkit.postPriorityEvent(fl);

In this way i can guarantee that you will receive focus on game component right away

Best Regards !

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

This has been asked many times previously, and in this situation the best solution is to not use a KeyListener. Instead use Key Bindings (click link), which behaves much better with regards to component focus.

Side recommendation: be sure to play your music off of the Swing event thread so as not to tie up this thread and freeze your GUI, and that all Swing calls be made on the Swing event thread.

Upvotes: 5

Related Questions