Jump to content

Need help with focus, I think!

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Master Kenth

Master Kenth

    Newbie

  • Members
  • Pip
  • 4 posts
I have a custom JPanel that implements KeyListener. It works fine when run from that class's main method, creating a new JFrame and adding a new instance of the JPanel in it.

But it doesn't work when I have a JFrame class create a new JFrame and then adding that JPanel to it. The window also becomes unresponsive but the code in the JPanel keeps running fine (I'm using a custom paint loop).

What is wrong? Also, when running from the JPanel it retains focus (as per isFocusOwner()) but not when running from the JFrame, even using requestFocus().

Minimal sample included as attachment. Help appreciated :)
[ATTACH]3842[/ATTACH]

Attached Files



#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
That's because the button you pressed will keep focus untill it reached the end of its actionPerformed.

Which means the button will release focus when NewFrame(); is done (Don't start methods with a capital letter)
Which means it will release focus when d.draw(); is ready.
Which means it will release focus when the program ends :)

To fix it, you should run the code from the ActionPerformed in a separate thread, so the actionPerformed code can end, so button can release focus. While in the background it will be running the code.


@Override

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == jb) {

            (new Thread(new Runnable(){

                public void run() {

                    NewFrame();

                }                

            })).start();

        }

    }



#3
Master Kenth

Master Kenth

    Newbie

  • Members
  • Pip
  • 4 posts
Ah I see :) I knew it was something with the focus and possibly the thread running but I just couldn'y connect it right. Also, the capital method thing was just on a whim. I usually don't :cool:

Thanks




2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users