Java 在进入主程序之前,如何提示用户输入密码?
我需要做的是用用户名和密码提示用户(身份验证在本地完成),如果它签出,用户将能够访问主程序体Java 在进入主程序之前,如何提示用户输入密码?,java,swing,user-interface,joptionpane,Java,Swing,User Interface,Joptionpane,我需要做的是用用户名和密码提示用户(身份验证在本地完成),如果它签出,用户将能够访问主程序体 public static void main(String[] args){ //String input = JOptionPane.showInputDialog("Enter password to continue: "); //input2 = Integer.parseInt(input); // followed by the creation of the main
public static void main(String[] args){
//String input = JOptionPane.showInputDialog("Enter password to continue: ");
//input2 = Integer.parseInt(input);
// followed by the creation of the main frame
new Cashier3();
Cashier3 frame = new Cashier3();
frame.setTitle("CASHIER 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
有什么快速的方法可以做到这一点吗?你可以简单地在你的程序中添加一个静态块来进行身份验证,这个静态块总是在main方法之前执行。如果用户无效,请使用
System.exit(0);
退出程序。否则程序将像往常一样开始执行
下面是一个示例程序,让您了解一些情况:
import java.awt.Color;
import javax.swing.*;
public class Validation extends JFrame
{
private static Validation valid = new Validation();
static
{
String choice = JOptionPane.showInputDialog(valid, "Enter Password", "Password", JOptionPane.PLAIN_MESSAGE);
if ((choice == null) || ((choice != null) && !(choice.equals("password"))))
System.exit(0);
}
private static void createAndDisplayGUI()
{
valid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
valid.setLocationRelativeTo(null);
valid.getContentPane().setBackground(Color.YELLOW);
valid.setSize(200, 200);
valid.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndDisplayGUI();
}
});
}
}
您可以使用showInputDialog获取用户名 和下面的代码来获取密码
JLabel label = new JLabel("Please enter your password:");
JPasswordField jpf = new JPasswordField();
JOptionPane.showConfirmDialog(null,
new Object[]{label, jpf}, "Password:",
JOptionPane.OK_CANCEL_OPTION);
并编写一个if条件来检查用户名和密码
if (!isValidLogin()){
//You can give some message here for the user
System.exit(0);
}
//如果登录被验证,那么用户程序将继续进行,这很有意义。我没有真正接触过静态块,直到现在才真正意识到它的必要性。谢谢,这使它更清楚了。@user976123:不客气,很高兴我能帮上忙。Regard请参阅关于如何格式化代码块的:)或下次只使用{}按钮。
String userName = userNameTF.getText();
String userPassword = userPasswordPF.getText();
if(userName.equals("xian") && userPassword.equals("1234"))
{
JOptionPane.showMessageDialog(null,"Login successful!","Message",JOptionPane.INFORMATION_MESSAGE);
// place your main class here... example: new L7();
}
else
{
JOptionPane.showMessageDialog(null,"Invalid username and password","Message",JOptionPane.ERROR_MESSAGE);
userNameTF.setText("");
userPasswordPF.setText("");
}