FocusTraversalKeysに矢印キーを追加してフォーカス移動
Total: 12783
, Today: 8
, Yesterday: 2
Posted by aterai at
Last-modified:
概要
デフォルトのTabキーに加えて、矢印キーでもフォーカス移動できるように設定します。
Screenshot
Advertisement
サンプルコード
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Set<AWTKeyStroke> forwardKeys = new HashSet<>(
focusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
focusManager.setDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys);
Set<AWTKeyStroke> backwardKeys = new HashSet<>(
focusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
backwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
backwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
focusManager.setDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardKeys);
View in GitHub: Java, Kotlin解説
上記のサンプルでは、デフォルトのフォーカストラバーサルキー(Tab、Shift+Tab)に加えて、上下左右の矢印キーでもフォーカス移動できるように設定しています。
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS
KeyEvent.VK_RIGHT
,KeyEvent.VK_DOWN
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS
KeyEvent.VK_LEFT
,KeyEvent.VK_UP
- 各
JFrame
やJDialog
に別々のFocusTraversalKeys
を設定したい場合は、以下のようにContainer#setFocusTraversalKeys
を使用する
Set<AWTKeyStroke> forwardKeys = new HashSet<>(
frame.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
frame.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys);
参考リンク
- KeyboardFocusManager (Java Platform SE 8)
- Container#setFocusTraversalKeys(...) (Java Platform SE 8)
- How to Use the Focus Subsystem
- Focusの移動