The default behavior when pressing the tabular key in a JTextArea
is to insert a tab spaces in the text area. In this example you’ll see how to change this to make the tab key to transfer focus to other component forward or backward.
The main routine can be found in the key listener section. When the tab key is pressed we will tell the text area to transfer to focus into other component. Let’s see the code snippet below.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TextAreaTabMoveFocus extends JFrame {
public TextAreaTabMoveFocus() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new TextAreaTabMoveFocus().setVisible(true));
}
private void initialize() {
setSize(500, 200);
setTitle("JTextArea TAB DEMO");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextField textField = new JTextField();
JPasswordField passwordField = new JPasswordField();
final JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
// Add key listener to change the TAB behavior in
// JTextArea to transfer focus to other component forward
// or backward.
textArea.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_TAB) {
if (e.getModifiersEx() > 0) {
textArea.transferFocusBackward();
} else {
textArea.transferFocus();
}
e.consume();
}
}
});
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(passwordField, BorderLayout.SOUTH);
}
}
The output of the code snippet above is:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Loved it, Was looking for that. Thanks alot:)
Thank you so much! This really helped. Peace!!!
Muchas gracias, saludos desde Colombia.
Thanks, it working very smoothly
The method
getModifiers()
from the typeInputEvent
is deprecated since version 9.And when I press the key after refocusing on the field before jumping it creates a tab within the
JTextArea
when I exit theJFrame
I have a function that if theJTextArea
is empty it returns true and it should return false since theJTextArea
field is not empty because tabs were created.Any solution?
Hi Daniel, the deprecated
getModifiers()
method can be replaced withgetModifiersEx()
method.