I will print related info if users focus on current window and press a key. However, it works for some keys like 'a' but not for 'tab'. Here is a simple demo:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class KeyBindingTest {
public static void main(String[] args) {
KeyBindingTest test = new KeyBindingTest();
test.createUI();
}
public void createUI(){
JFrame frame = new JFrame("KeyBinding Test");
MainPanel mainPanel = new MainPanel();
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@SuppressWarnings("serial")
class MainPanel extends JPanel{
public MainPanel(){
setPreferredSize(new Dimension(200, 200));
//========================key binding============================
requestFocusInWindow();
String aString = "aStr";
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aString);
getActionMap().put(aString, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("a is typed");
}
});
String tabString = "tabStr";
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), tabString);
getActionMap().put(tabString, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("tab is typed");
}
});
}
}
}
What can I do to reach it? Thanks in advance.
interesting issue with TAB, looks like as bug, because isn't possible to get, capture the KeyChar from TAB without using Shift_TAB before, event from TAB is somehow consumed elsewhere, no idea whats happened
my view - there is an issue with Focus because key TAB is used by Native OS and as built_in KeyBindings in Swing,
opposite issue with TAB and Shift_TAB in question Java Swing: how to stop unwanted shift-tab keystroke action
maybe someone has explanation how to catch a TAB event
TAB is used as KeyBindings (built_in in API) for many JComponents or navigations inside Container contains more than one JComponent
funny output from AWTEventListener (win8_64b/Java7_xxx)
from code
I think it should work if you put
in your
MainPanel
constructor. At least it works for e.g.addKeyListener(...);
Quote from How to Use the Focus Subsystem (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features) (suggested by @alex2410(link to @camickr post) and @mKorbel):
So if you want to make the Tab KeyBinding action work in the panel, you need to remove the Tab key focus navigation from the panel.