我正在学习 Java,在我的一项练习中,我必须做一个日志记录框架,在按下取消按钮后、输入 ID 或密码之前显示警告。
import javax.swing.JOptionPane;
public class Authenticator {
public static void main(String args[]) {
String username = JOptionPane.showInputDialog("ID:");
String password = JOptionPane.showInputDialog("PASSWORD:");
if (
username != null && password != null &&
(
(username.equalsIgnoreCase("bburd") && password.equalsIgnoreCase("whale")) ||
(username.equalsIgnoreCase("hritter") && password.equalsIgnoreCase("preakston")) ||
(username.equalsIgnoreCase("epiekos") && password.equalsIgnoreCase("simplus"))
)
)
{
JOptionPane.showMessageDialog(null, "YOU'RE IN");
} else {
Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "NO INFORMATION", "WARNING",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
}
}
}
我尝试使用 JOptionPane 类,但单击按钮后没有出现警告。它出现在程序的末尾。
您遇到的问题是因为显示警告消息的代码是在密码输入对话框之后执行的。要在输入密码之前显示警告消息,您应该将显示警告消息的代码移动到适当的位置。
这是代码的修改版本,在询问密码之前会显示警告消息:
import javax.swing.JOptionPane;
public class Authenticator {
public static void main(String args[]) {
String username = JOptionPane.showInputDialog("ID:");
// Check if username is null or empty
if (username == null || username.isEmpty()) {
// Display warning message if username is null or empty
Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "NO INFORMATION", "WARNING",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
} else {
// Continue asking for password if username is provided
String password = JOptionPane.showInputDialog("PASSWORD:");
if (
password != null &&
(
(username.equalsIgnoreCase("bburd") && password.equalsIgnoreCase("whale")) ||
(username.equalsIgnoreCase("hritter") && password.equalsIgnoreCase("preakston")) ||
(username.equalsIgnoreCase("epiekos") && password.equalsIgnoreCase("simplus"))
)
) {
JOptionPane.showMessageDialog(null, "YOU'RE IN");
} else {
Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "NO INFORMATION", "WARNING",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
}
}
}
}
这应该有效