Java GUI 键盘响应事件 与 swing组件焦点问题
这个一个简单画图板界面,
JFrame.java(类名随意取的)
this.setJMenuBar(getJJMenuBar());
this.setContentPane(getJContentPane());
contentpanel用的是BorderLayout, North是toolbar,Center是画图的Panel,South是再下面提到的rootpanel.java
初始化的时候我使得JButtonDraw.requestFocusInWindow(); //工具栏倒数第二个Button获得焦点
rootpanel.java 键盘响应事件在这个类中比较方便
然后,下面是响应键盘输入的
(
WHEN_IN_FOCUSED_WINDOW 当组件处于焦点窗口中时侦听到的键盘事件;
WHEN_FOCUSED 当组件获得焦点后侦听到的键盘事件(系统默认);
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 组件祖先获得焦点。)
InputMap inputmap = this.getInputMap(WHEN_IN_FOCUSED_WINDOW);
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "r");
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "l");
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "f");
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "e");
ActionMap actionmap = this.getActionMap();
actionmap.put("f", new MyAction('f')); //first
actionmap.put("e", new MyAction('e')); //end
actionmap.put("l", new MyAction('l')); //left
actionmap.put("r", new MyAction('r')); //right
MyAction类 键盘响应事件应该没错
问题是不管我怎么试试,键盘响应不了,
但如果我在初始化界面的时候,JFrame.requestFocus();键盘事件就能响应
是因为我的Focus设置在了toolbar上的按钮上了?
swing
focus
键盘响应?GUI
------解决方案-------------------- 楼主你不是自己解决问题了吗
引用 To fire keyboard events, a component must have the keyboard focus.
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
------解决方案-------------------- 不用单独绑
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
public class KeyStrokeTest extends JFrame{
public static void main(String[] args) {
new KeyStrokeTest();
}
public KeyStrokeTest(){
setVisible(true);
setSize(300,300);
JToolBar jToolBar=new JToolBar();
JButton jb1=new JButton("aa");
JButton jb2=new JButton("bb");
jToolBar.add(jb1);
jToolBar.add(jb2);
add(jToolBar);
ActionMap actionmap = jToolBar.getActionMap();
InputMap iMap=jToolBar.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
actionmap.put("r", new MyAction('r')); //right
iMap.put(KeyStroke.getKeyStroke("F2"), "r");
}
}
class MyAction implements Action{
char r;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println(r);
}