Java applet maintaining focus with multiple JPanels
I wrote a Java applet that uses multiple JPanels. One for the main menu, one for the high scores list, one for the game itself, and one for a final end screen that shows the score and asks the user to input his/her name.
On Mac OS X, once one JPanel gets focus (using MouseListener or with a Timer), the focus is easily switched to new JPanels. On Windows, however, you have to click each time with each screen to manually get the focus back.
My question is, is there an elegant, cross-platform solution to always keeping focus within the Applet's top-most JPanel, even when the top-level JPanel changes?
Here's a sample code of what I'm doing to switch between JPanels:
public void showMainMenu() {
if (endScreen != null) {
endScreen.stop();
getContentPane().remove(endScreen);
endScreen = null;
}
if (highScoreView != null) {
getContentPane().remove(highScoreView);
highScoreView = null;
}
if (gameView != null) {
gameView.sto开发者_如何学运维p();
getContentPane().remove(gameView);
gameView = null;
}
if (mainMenu == null) {
mainMenu = new MainMenu(d, this);
}
getContentPane().add(mainMenu);
forceRequestFocus();
validate();
repaint();
}
I tried using a workaround I found on here to use a non-repeating Timer to get the focus of the JPanel, so the user doesn't have to click on it. Only problem is, that it only works once. After a new JPanel replaces another, focus is lost and can only be regained with a mouse click.
private void forceRequestFocus() {
Timer focusTimer = new Timer(5, new RequestFocusActionListener());
focusTimer.setRepeats(false);
focusTimer.start();
}
private class RequestFocusActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (highScoreView != null) {
highScoreView.requestFocusInWindow();
}
else if (mainMenu != null) {
mainMenu.requestFocusInWindow();
}
else if (gameView != null) {
gameView.requestFocusInWindow();
}
else if (endScreen != null) {
endScreen.requestFocusInWindow();
}
}
}
Ok, I figured it out. I can use the Timer
to get the first JPanel
to get focus, and then when I switch to another panel, I call transferFocus()
on the main menu to the new view.
精彩评论