Bamdad Dashtban
Bamdad Dashtban

Reputation: 354

Grab focus to a JPanel in a JLayeredPane

I have a JLayeredPane with 2 layers

the first layer is a JPanel Wrapping an Image. the second layer is another object which extends JPanel called ResizableRectangle and implements KeyListener.

I've overrode the KeyPressed method but it doesn't receive the keyPressed event and the method doesn't get invoked.

I've set the setFocusEnable(true) and used grabFocus(), requestFocus() and requestFocusInWindows() but all of them return false.

I figured out when I press tab after the the JFrame loads , the Focus goes to the panel that I want , and the listener gets the events.

I've added a KeyListener to the JLayeredPane and it works fine but the problem is that i want to add listener to the panel not the layeredPane.

Upvotes: 2

Views: 1680

Answers (1)

mKorbel
mKorbel

Reputation: 109815

I hope that you put Image or ImageIcon to the JLabel then add to the JLabel MouseListener

then just to call

EventQueue.invokeLater(new Runnable() {

     @Override
     public void run() {
        myPanel.grabFocus();
        myPanel.requestFocus();//or requestFocusInWindows();          
     }
});

Upvotes: 2

Related Questions