如何使JFrame保持获得焦点?

whisky020 2011-06-13 11:51:35
我的程序是类似金山打字通的打苹果键盘游戏,我是让JFrame addKeyboardListener的,刚打开程序能成功监听
但是每当我按下了一个button后,JFrame就失去焦点了,我试了在button的事件监听中调用jFrame.requestFocusInWindow();也不行
有什么方法能使我操作完button后,使JFrame重新获回焦点呢?
我查了API,好像 setGlobalPermanentFocusOwner,这个“设置持久焦点所有者”最适合的,但我不知道怎么用,这个函数括号里应该输入些什么内容?可以举个完整的使用此函数的例子吗?感谢各位
protected void setGlobalPermanentFocusOwner(Component permanentFocusOwner)
...全文
700 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
福来哥 2011-06-13
  • 打赏
  • 举报
回复
protected void setGlobalPermanentFocusOwner(Component permanentFocusOwner)

This method does not actually set the focus to the specified Component.
Use Component.requestFocus() or Component.requestFocusInWindow() to change the focus owner, subject to platform limitations
wain020 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 peng_hao1988 的回复:]

可以给button添加一个和Frame一样的监听器,一样的handler。不知这样可否?
[/Quote]我也是楼主,我换个帐号(因为连续只能回复三次)
这个方法也真的可以啊,看来有不少方法能实现呢,CSDN真强大,也可能我太菜了,呵呵
whisky020 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 softroad 的回复:]

addFocusListener

失去焦点后再重新设定,不知可行不。
[/Quote]这个我之前试过,addFocusListener提示说此方法对JFrame不可用,不知为什么
whisky020 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用楼主 whisky020 的回复:]
我试了在button的事件监听中调用jFrame.requestFocusInWindow();也不行
[/Quote]
现在可以了,原来我之前,在button监听事件中,把焦点重新设到panel上,没有弄到Jframe,原来自己弄错了,
都怪自己粗心
感谢各位的热心回答,#6楼的Mybeautiful,说法正确
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button){
frame.requestFocusInWindow();
whisky020 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 ethenjean 的回复:]

引用 2 楼 whisky020 的回复:
You know , I had used that way before asking the question here ,which is using Component.requestFocus() or Component.requestFocusInWindow(), but unfortunately,it could not be w……
[/Quote]你说得对,我发表后,就发现写错了,当时就想编缉,可是没权限,你真眼利,O(∩_∩)O
Mybeautiful 2011-06-13
  • 打赏
  • 举报
回复
在buttong监听器的最后,把焦点重设到frame上,可行否?
ethenjean 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 whisky020 的回复:]
You know , I had used that way before asking the question here ,which is using Component.requestFocus() or Component.requestFocusInWindow(), but unfortunately,it could not be worked,
however,thank you all the same.[/Quote]

我觉得应该是it did not work,而不是it could not be worked!
桃园闲人 2011-06-13
  • 打赏
  • 举报
回复
可以给button添加一个和Frame一样的监听器,一样的handler。不知这样可否?
softroad 2011-06-13
  • 打赏
  • 举报
回复
addFocusListener

失去焦点后再重新设定,不知可行不。
whisky020 2011-06-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 feg545 的回复:]

protected void setGlobalPermanentFocusOwner(Component permanentFocusOwner)

This method does not actually set the focus to the specified Component.
Use Component.requestFocus() or Component.reques……
[/Quote]
You know , I had used that way before asking the question here ,which is using Component.requestFocus() or Component.requestFocusInWindow(), but unfortunately,it could not be worked,
however,thank you all the same.

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧