我有一些简单的代码,我试图将键盘事件输入到 Java 小程序中。使用 appletviewer 运行代码时运行良好,但是当我从浏览器加载它时(尝试了 Chrome 和 Firefox),JApplet 不会专注于点击。
使用 Applet 而不是 JApplet 尝试完全相同的代码没有问题。
这是我的代码:
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);
}
}