Java 带有用户名和密码输入的 JOptionPane
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18395615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JOptionPane with username and password input
提问by Gerret
I have my own Dialog pop up with two textfields, two JLabel and a "ok" JButton. The pop up is a login window. The window works perfect I just want to know how I am able to add a "cancel" JButton, so the user is able to cancel the login.
我有自己的 Dialog 弹出窗口,其中包含两个文本字段、两个 JLabel 和一个“ok”JButton。弹出窗口是一个登录窗口。该窗口工作正常我只想知道我如何能够添加“取消”JButton,以便用户能够取消登录。
Here is my code for the window:
这是我的窗口代码:
public Hashtable<String, String> login(JFrame frame) {
Hashtable<String, String> logininformation = new Hashtable<String, String>();
JPanel panel = new JPanel(new BorderLayout(5, 5));
JPanel label = new JPanel(new GridLayout(0, 1, 2, 2));
label.add(new JLabel("E-Mail", SwingConstants.RIGHT));
label.add(new JLabel("Password", SwingConstants.RIGHT));
panel.add(label, BorderLayout.WEST);
JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2));
JTextField username = new JTextField();
controls.add(username);
JPasswordField password = new JPasswordField();
controls.add(password);
panel.add(controls, BorderLayout.CENTER);
JOptionPane.showMessageDialog(frame, panel, "login", JOptionPane.QUESTION_MESSAGE);
logininformation.put("user", username.getText());
logininformation.put("pass", new String(password.getPassword()));
return logininformation;
}
If you need it, here is a screenshot of the login window:
如果您需要,这里是登录窗口的屏幕截图:
If you would click on the "x" at the right corner, it closes too. But I want a cancel JButton, if it is easily possible.
如果您单击右上角的“x”,它也会关闭。但我想要一个取消 JButton,如果很容易的话。
- Thank you for help
- 谢谢你的帮助
采纳答案by Ravi Thapliyal
You need to use an OK
, CANCEL
type confirm dialog.
您需要使用OK
,CANCEL
类型确认对话框。
JOptionPane.showConfirmDialog(
frame, panel, "login", JOptionPane.OK_CANCEL_OPTION);
回答by Vimal Bera
You can use dispose()
function on JFrame to close the frame when you click on the button. Like this
dispose()
当您单击按钮时,您可以使用JFrame 上的函数来关闭框架。像这样
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
frameName.dispose();
}
});
回答by Prasad Kharkar
You need to use JOptionPage.showOptionDialog()which enables to add buttons
您需要使用JOptionPage.showOptionDialog()来添加按钮