Подтвердить что ты не робот

Перемещение фокуса с JTextArea с помощью клавиши табуляции

Как указано, я хочу изменить поведение TAB по умолчанию в JTextArea (так, чтобы оно действовало как JTextField или аналогичный компонент)

Здесь действие события

private void diagInputKeyPressed(java.awt.event.KeyEvent evt) {
    if(evt.KEY_PRESSED == java.awt.event.KeyEvent.VK_TAB) {
        actionInput.transferFocus();
    }
}

И вот слушатель

diagInput.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(java.awt.event.KeyEvent evt) {
        diagInputKeyPressed(evt);
    }
});

Я тоже пробовал evt.KEY_TYPED без радости.

Любые идеи?

быстрое редактирование: я также попробовал requestFocus() вместо transferFocus()

4b9b3361

Ответ 1

В соответствии с этот класс:

/**
 * Some components treat tabulator (TAB key) in their own way.
 * Sometimes the tabulator is supposed to simply transfer the focus
 * to the next focusable component.
 * <br/>
 * Here s how to use this class to override the "component default"
 * behavior:
 * <pre>
 * JTextArea  area  = new JTextArea(..);
 * <b>TransferFocus.patch( area );</b>
 * </pre>
 * This should do the trick. 
 * This time the KeyStrokes are used.
 * More elegant solution than TabTransfersFocus().
 * 
 * @author kaimu
 * @since 2006-05-14
 * @version 1.0
 */
public class TransferFocus {

    /**
     * Patch the behaviour of a component. 
     * TAB transfers focus to the next focusable component,
     * SHIFT+TAB transfers focus to the previous focusable component.
     * 
     * @param c The component to be patched.
     */
    public static void patch(Component c) {
        Set<KeyStroke> 
        strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
        c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
        strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
        c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
    }
}

Обратите внимание, что patch() может быть еще короче, согласно Джошуа Голдбергу в комментариях, поскольку цель состоит в том, чтобы вернуть поведение по умолчанию, переопределенное JTextArea:

component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERS‌​AL_KEYS, null);
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERS‌​AL_KEYS, null);

Это используется в вопросе "Как изменить поведение ключа табуляции в JTextArea?"


предыдущая реализация действительно включала Listener, а a transferFocus():

   /**
     * Override the behaviour so that TAB key transfers the focus
     * to the next focusable component.
     */
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_TAB) {
            System.out.println(e.getModifiers());
            if(e.getModifiers() > 0) a.transferFocusBackward();
            else a.transferFocus(); 
            e.consume();
        }
    }

e.consume();, возможно, было тем, что вы пропустили, чтобы заставить его работать в вашем случае.