Keyboard input in Java Applet
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) 开发者_StackOverflow社区{}
});
}
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.
I think you are running into the plugin focus issue: in many modern browser a plugin only gains focus through either the user clicking on it or using Javascript. This typically affects Flash but it might be that it also affects applets. Try Adobe's recommendations at http://kb2.adobe.com/cps/155/tn_15586.html.
Let me know if that works for you.
精彩评论