我需要一种方法来编写一些代码来处理单击 JOptionPane 中的按钮时的事件。我实际上是在使用 JOptionPane 插入用户名和密码,如果单击正确且确定按钮,则 JOptionPane 消失并且父 JFrame 保持 Activity 状态,如果单击取消按钮,程序退出。我下面的示例代码仅显示 JOptionpane 并单击任何按钮将其关闭 `JPanel 面板 = new JPanel(); panel.setLayout(new GridLayout(4, 1)); //创建一个带有文本的标签(用户名) JLabel username = new JLabel("用户名");
//Create a label with text (Password)
JLabel password = new JLabel("Password");
//Create text field that will use to enter username
JTextField textField = new JTextField(12);
//Create password field that will be use to enter password
JPasswordField passwordField = new JPasswordField(12);
//Add label with text (username) into created panel
panel.add(username);
//Add text field into created panel
panel.add(textField);
//Add label with text (password) into created panel
panel.add(password);
//Add password field into created panel
panel.add(passwordField);
//Show JOptionPane that will ask user for username and password
JOptionPane.showConfirmDialog(mainFrame, panel, "Enter username and password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);`
最佳答案
这些对话框返回一个 int
值,可以解释为以下之一:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
例如,
final int option = JOptionPane.showConfirmDialog(mainFrame, panel, "Enter username and password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.OK_OPTION){
// OK was pressed. Now do stuff.
}
else if(option == JOptionPane.CANCEL_OPTION){
// Cancel was pressed. Now do stuff.
}
关于java - 如何处理 JOptionPane.showConfirmDialog 中的选项类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9704890/