I have some simple code where I'm trying to get keyboard events into a Java applet. The code runs just fine when being run with appletviewer, but when I'm loading it from a browser (tried both Chrome and Firefox), the JApplet won't get focus on click.
Trying exactly the same code with Applet instead of JApplet works without a problem.
Here's my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
String s = "";
public void init() {
setFocusable(true);
setEnabled(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
s = "KEY PRESSED: " + e.getKeyCode();
repaint();
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
boolean ret = requestFocusInWindow();
s = "requestFocusInWindow: " + ret;
repaint();
}
});
requestFocusInWindow();
}
public void start() {
requestFocusInWindow();
}
public void paint(Graphics g) {
super.paint(g);
requestFocusInWindow();
g.setColor(Color.BLACK);
s = "Focus owner: " + isFocusOwner() + ", " + s;
g.drawString(s, 24, 24);
}
}