Selon 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);
}
}
Notez que patch()
peut être encore plus court, selon Joshua Goldberg dans the comments, puisque le but est pour récupérer les comportements par défaut remplacés par JTextArea
:
component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
C'est utilisé en question « How can I modify the behavior of the tab key in a JTextArea
? »
Le previous implementation impliqué en effet un Listener
, et 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();
aurait pu être ce que vous avez manqué de le faire fonctionner dans votre cas .
Très similaire à http://stackoverflow.com/questions/5042429/how-can-i-modify-the-behavior-of-the-tab-key-in-a-jtextarea – Pops