KeyEvent not being generated by JFrame java?
I have a java program with a JFrame and 3 JButtons in it. I have added a keylistener to jframe. When i run the program a jframe window is opened and the first button is selected by default. My problem is that a KeyEvent is not being generated by this JFrame. Now, besides adding a KeyListener to th开发者_运维知识库e jframe, i also added a KeyListener to the buttons. Now the keyevent is being generated by the buttons.
How do I make the JFrame generate KeyEvent instead of the JButton generating them ??
Actually, my main purpose is building keyboard shortcuts for the buttons.
Have a look here How to Use Key Bindings.
An alternative to keylistener.
Here is a little Example it has a Button with focus and process a KeyEvent (F2).
On F2-clicked the Key-Binding process a ButtonClick which performed a System.out
print.
public class Example {
static public void main( String[] s ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout( new BorderLayout() );
frame.setBounds( 50, 50, 600, 600 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
final JButton button = new JButton( new AbstractAction("MyButton") {
@Override
public void actionPerformed( ActionEvent e ) {
System.out.println("Button Clicked");
}
});
frame.getContentPane().add( button );
frame.getRootPane().setDefaultButton( button );
KeyStroke f2 = KeyStroke.getKeyStroke("F2");
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(f2, "clickButton");
frame.getRootPane().getActionMap().put("clickButton", new AbstractAction() {
@Override
public void actionPerformed( ActionEvent e ) {
button.doClick();
}
});
frame.setVisible( true );
// the Button has the focus
button.requestFocus();
// generate a KeyEvent 'F2'
KeyboardFocusManager.getCurrentKeyboardFocusManager().dispatchKeyEvent( new KeyEvent( frame, KeyEvent.KEY_PRESSED, 0, f2.getModifiers(), f2.getKeyCode(), f2.getKeyChar() ) );
}
});
}
}
The key event is called on the currently focused component (which is usually not the JFrame
)
精彩评论