2009-02-08 11 views
29

Como se ha dicho, quiero cambiar el comportamiento pestaña predeterminada dentro de un JTextArea (de modo que actúe como un componente JTextField o similar)Mover el foco de JTextArea mediante la ficha clave

Aquí está la acción del evento

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

Y aquí está el oyente

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

he intentado evt.KEY_TYPED así sin alegría.

¿Alguna idea?

edición rápida: También he intentado requestFocus() en lugar de transferFocus()

+1

Muy similar a http://stackoverflow.com/questions/5042429/how-can-i-modify-the-behavior-of-the-tab-key-in-a-jtextarea – Pops

Respuesta

25

Según this class:

/** 
* 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's 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); 
    } 
} 

Tenga en cuenta que patch() puede ser incluso más corto, según Joshua Goldberg en the comments, ya que el objetivo es para recuperar comportamientos predeterminados anulados por JTextArea:

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

Esto se utiliza en cuestión "How can I modify the behavior of the tab key in a JTextArea?"


El previous implementation involucrados en efecto un Listener, y la de un 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(); podría haber sido lo que se ha perdido para que funcione en su caso .

+0

necesario para cambiar a getKeyCode () y evt.consume() - evt.consume() eliminó el carácter de tabulación y el uso de getKeyCode() le permite mover el foco con éxito usando tab. Muchas gracias :) –

+0

De nada. Me pregunto si la primera implementación (la que modifica las FocusTraversalKeys de un Componente) no es "limpia" de alguna manera, aunque ... – VonC

+0

wow, buena respuesta, siempre con la misma atención ejemplar al detalle :) –

Cuestiones relacionadas