Topic: JPanel能不能获得键盘的事件?

  Print this page

1.JPanel能不能获得键盘的事件? Copy to clipboard
Posted by: mannajava
Posted on: 2004-06-02 09:36

几种情况:
1、在一个没有容纳其他对象的JPanel上,注册addKeyListener事件,运行后JPanel不响应键盘事件。
2、在一个容纳了一个对象的JPanel上,对JPanel注册addKeyListener事件,运行后JPanel不响应键盘事件。
3、在一个容纳了一个JButton对象的JPanel上,对JButton注册相同的addKeyListener事件,运行后JButton可以响应键盘事件。
为什么?

2.Re:JPanel能不能获得键盘的事件? [Re: mannajava] Copy to clipboard
Posted by: tangming
Posted on: 2004-06-02 13:15

大概是因为KeyEvent继承自InputEvent,
应该只对能够Input的Component相应吧。

3.Re:JPanel能不能获得键盘的事件? [Re: mannajava] Copy to clipboard
Posted by: samuel
Posted on: 2004-06-03 09:45

Try it:

public class KeyPanel extends JPanel
{
public KeyPanel()
{
enableEvents(AWTEvent.KEY_EVENT_MASK) ;
addKeyListener(<your listener>Wink ;
}
}

4.Re:JPanel能不能获得键盘的事件? [Re: samuel] Copy to clipboard
Posted by: mannajava
Posted on: 2004-06-03 12:36

samuel wrote:
Try it:

public class KeyPanel extends JPanel
{
public KeyPanel()
{
enableEvents(AWTEvent.KEY_EVENT_MASK) ;
addKeyListener(<your listener>Wink ;
}
}


不行啊.

5.Re:JPanel能不能获得键盘的事件? [Re: mannajava] Copy to clipboard
Posted by: samuel
Posted on: 2004-06-04 15:57

Try it again:

enableEvents(AWTEvent.KEY_EVENT_MASK);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStorke.getKeyStorke("F2"), "actionName");
getActionMap().put("actionName",
new new AbstractAction("actionName") {
public void actionPerformed(ActionEvent evt) {
System.out.println(evt);
}
});

---------------------
It can response the F2 key, if it make a mistake, let me know.


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923