Pasar el foco de un campo a otro - Swing
Hola a todos,
mi pregunta es la siguiente: estoy diseñando una interfaz gráfica con Swing. Tengo un formulario con unos campos de texto y me gustaría que si escribo en uno de ellos 4 caracteres el foco lo reciba otro campo de texto (el siguiente). No se qué es lo que tengo que añadirle al campo de texto, actionListener, keyListener, focusListener...
Me puede echar alguien una mano?
Gracias.
mi pregunta es la siguiente: estoy diseñando una interfaz gráfica con Swing. Tengo un formulario con unos campos de texto y me gustaría que si escribo en uno de ellos 4 caracteres el foco lo reciba otro campo de texto (el siguiente). No se qué es lo que tengo que añadirle al campo de texto, actionListener, keyListener, focusListener...
Me puede echar alguien una mano?
Gracias.
Puede que este código te sirva de ayuda. Es muy simple, pero te puede dar alguna pista de cómo hacer.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MovingFocus extends JFrame{
private static final long serialVersionUID = 4140949677249706266L;
public MovingFocus() {
this.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField(5);
final JTextField textField2 = new JTextField(5);
this.getContentPane().add(textField1);
this.getContentPane().add(textField2);
textField1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (textField1.getText().length() >= 4) {
textField2.requestFocusInWindow();
}
}
});
this.pack();
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new MovingFocus().setVisible(true);
}
});
}
}
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MovingFocus extends JFrame{
private static final long serialVersionUID = 4140949677249706266L;
public MovingFocus() {
this.getContentPane().setLayout(new FlowLayout());
final JTextField textField1 = new JTextField(5);
final JTextField textField2 = new JTextField(5);
this.getContentPane().add(textField1);
this.getContentPane().add(textField2);
textField1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (textField1.getText().length() >= 4) {
textField2.requestFocusInWindow();
}
}
});
this.pack();
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new MovingFocus().setVisible(true);
}
});
}
}