java applet 输入代理设置,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) {}

});

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值