What is the best way to listen for keyboard input in a Java Applet?
I have an applet which opens a JFrame and I am using a KeyListener to listen for keyboard input. This works fine in my development environment (eclipse), but when I run the applet through a browser (I have tried Firefox and IE) it does not respond to keyboard events.
However, if I run the applet and then minimize and maximize the frame, it works.
I have tried setting focus to the JFrame in many different ways and also programmatically minimizing and maximizing it, but to no effect.
I have also tried key bindings, but with the same problem.
I have trimmed my code down to the barest essentials of the problem and pasted it below.
Can someone see what I am doing wrong or suggest a better solution?
public class AppletTest extends Applet
{
private GuiTest guiTest;
public void init() {
guiTest = new GuiTest();
final AppletTest at = this;
guiTest.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent ke) {
at.keyPressed(ke);
}
public void keyReleased(KeyEvent ke) {}
public void keyTyped(KeyEvent e) {}
});
}
private void keyPressed(KeyEvent ke)
{
System.out.println("keyPressed "+KeyEvent.getKeyText(ke.getKeyCode()));
getGuiTest().test(KeyEvent.getKeyText(ke.getKeyCode()));
}
}
public class GuiTest extends JFrame {
String teststring = "?";
public GuiTest()
{
setSize(100,100);
setEnabled(true);
setVisible(true);
setFocusable(true);
requestFocus();
requestFocusInWindow();
toFront();
}
public void test(String t)
{
teststring = t;
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
g.drawString(teststring, 50, 50);
}
}
解决方案
I solved the problem. If I create the JFrame following a button press or mouse event on the applet, the key listener on the JFrame works. Apparently, creating the frame from Applet.init() means that key listeners do not function correctly when opened through a browser.
However, the question remains - why? If someone can explain this, I would greatly appreciate it.
I thought it might be because the frame should be created on the event dispatch thread, but using SwingUtilities.invokeLater or invokeAndWait did not work.