我会改用键绑定 API,键侦听器往往很麻烦,通常会生成很多混乱的if-else
语句。
public class KeyBindingsTransfer {
public static void main(String[] args) {
new KeyBindingsTransfer();
}
public KeyBindingsTransfer() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TransferPane());
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class TransferPane extends JPanel {
private JTextArea left;
private JTextArea right;
public TransferPane() {
setLayout(new GridLayout(1, 2, 4, 4));
left = new JTextArea();
right = new JTextArea();
add(left);
add(right);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, true), "transferOnAlt");
ActionMap actionMap = getActionMap();
actionMap.put("transferOnAlt", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked");
if (left.hasFocus()) {
right.requestFocusInWindow();
} else if (right.hasFocus()) {
left.requestFocusInWindow();
}
}
});
}
}
}