Reputation: 453
In my program I have a JTabbedPane which requests focus to listen to some key events, and it works fine on my mac. However when I switch over to a Windows machine, the focus seems to be lost. Key events can't be listened to anymore.
I have setRequestFocusEnabled(true)
as well in windows, which I didn't need on my mac.
How can I fix this?
Upvotes: 0
Views: 617
Reputation: 168845
From the JavaDocs for requestFocus()
:
Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of
requestFocusInWindow(boolean)
Upvotes: 1
Reputation: 1725
I had this problem myself, you need to use keybindings to get it working properly. You bind the key stroke to particular action :). The inputmap is then linked to the actionmap via the String key (in my example "space"). You can either use an anonymous inner AbstractAction class, though it may throw errors if you are calling non final variables. So in that class call a new private class that extends AbstractAction
JPanel component = (JPanel)frame.getContentPane();
//THIS IS THE KEY BINDING CODE
component.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
component.getActionMap().put("space", (new AbstractAction(){
public void actionPerformed(ActionEvent e){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
grid.stepGame();
}
},250, 250);
}}));
}
Upvotes: 1
Reputation: 20813
requestFocus
, is discouraged because it tries to give the focus to the component's window, which is not always possible.In modern JDKs, you should stick with the requestFocusInWindow
method
Did you try that method ?
Upvotes: 1