'How to select text fields using tab key in java

When I press tab key on the keyboard I want to select my text fields in above order.how to do that?
Solution 1:[1]
Try this example....
package com.Demo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
@SuppressWarnings("serial")
public class TabTest extends JFrame {
public TabTest() {
initialize();
}
private void initialize() {
setSize(300, 300);
setTitle("JTextArea TAB DEMO");
setDefaultCloseOperation(JFrame.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 behaviour 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.getModifiers() > 0) {
textArea.transferFocusBackward();
} else {
textArea.transferFocus();
}
e.consume();
}
}
});
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(passwordField, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TabTest().setVisible(true);
}
});
}
}
Solution 2:[2]
jTextField1.setNextFocusableComponent(jTextField2);
jTextField2.setNextFocusableComponent(jTextField3);
jTextField3.setNextFocusableComponent(jTextField4);
jTextField4.setNextFocusableComponent(jTextField5);
try this :)
Solution 3:[3]
Try this:
txtfld.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
txtfld.setText("aaa");
}
@Override
public void focusLost(FocusEvent e) {
...
}
});
see more complete code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Iren Patel |
| Solution 2 | Shinwar ismail |
| Solution 3 | ParisaN |
