gpt4 book ai didi

Java "JTextField.requestFocus()"在 JOptionPane 中不工作

转载 作者:行者123 更新时间:2023-11-30 07:09:47 28 4
gpt4 key购买 nike

我试图请求关注第一个用户名字段,但它没有关注文本字段。这是我的代码:

JTextField username = new JTextField();
JTextField password = new JPasswordField();
JTextField prefix = new JTextField();
username.requestFocus();
Object[] message = {
"Username:", username,
"Password:", password,
"Prefix:", prefix
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
username.requestFocus();
if (option == JOptionPane.OK_OPTION) {
return ls.login(username.getText(), password.getText(), prefix.getText());
} else {
return false;
}

如何请求用户名文本字段的焦点?

最佳答案

方法如下:

final JTextField username = new JTextField();
JTextField password = new JPasswordField();
JTextField prefix = new JTextField();
JPanel gridLayout = new JPanel(new GridLayout(6, 1));
gridLayout.add(new JLabel("Username:"));
gridLayout.add(username);
gridLayout.add(new JLabel("Password:"));
gridLayout.add(password);
gridLayout.add(new JLabel("Prefix:"));
gridLayout.add(prefix);

username.addAncestorListener(new AncestorListener() {
@Override
public void ancestorRemoved(AncestorEvent pEvent) {
}

@Override
public void ancestorMoved(AncestorEvent pEvent) {
}

@Override
public void ancestorAdded(AncestorEvent pEvent) {
// TextField is added to its parent => request focus in Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
username.requestFocusInWindow();
}
});
}
});

int option = JOptionPane.showConfirmDialog(null, gridLayout, "Login",
JOptionPane.OK_CANCEL_OPTION);

我只是用 JPanel 对象替换了您的 Object[] message,并使用 AncestorListener 在添加文本字段时收到通知给它的 parent 。

注意:我不知道为什么它不适用于您的 Object[] 消息

关于Java "JTextField.requestFocus()"在 JOptionPane 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700231/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com