Problem to focus JTextField
- by Tom Brito
I have used the approach of the ComponentListener to call focus in JTextField within a dialog, but for this case is just not working, I don't know why. It shows the focus in the text field and fast change to the button. Run and see:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class User {
private String username = "";
private String password = "";
public User() {
// default constructor
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
/** Create a panel containing the componet and tha label. */
public JPanel createLabeledComponent(JLabel label, Component comp) {
GridLayout layout = new GridLayout(2, 1);
JPanel panel = new JPanel(layout);
panel.add(label);
panel.add(comp);
label.setLabelFor(comp);
return panel;
}
public void showEditDialog() {
JLabel usernameLbl = new JLabel(username);
final JTextField usernameField = new JTextField();
usernameField.setText(username);
JPanel usernamePnl = createLabeledComponent(usernameLbl, usernameField);
JLabel passwordLbl = new JLabel(password);
JPasswordField passwordField = new JPasswordField(password);
JPanel passwordPnl = createLabeledComponent(passwordLbl, passwordField);
Object[] fields = { "User:", usernamePnl, "Password:", passwordPnl };
JOptionPane optionPane = new JOptionPane(fields, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null);
JDialog dialog = optionPane.createDialog("User Data");
dialog.addComponentListener(new ComponentListener() {
public void componentShown(ComponentEvent e) {
usernameField.requestFocusInWindow();
}
public void componentResized(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentHidden(ComponentEvent e) {}
});
dialog.setVisible(true);
}
public static void main(String[] args) {
new User().showEditDialog();
}
}
Any idea how to solve this?