我正在为游戏创建登录机制。如果用户输入了无效的用户名 - 密码组合,则会出现一个对话框,告诉他们错误。但是,当我在对话框中单击“确定”时,上一个表单中的所有组件都将变为非活动状态。
以下是我的事件处理程序方法代码:
//Event Handler
public void actionPerformed(ActionEvent e){
Scanner fileScan = null;
Scanner passwordScan = null;
String lineVar;
int lineCount=0;
//Opens the "Create Account" form
if (e.getSource()==CreateNew){
new CreateAccount();
}
//user tries to login
else if(e.getSource()==submit){
Inputuser = user.getText();
InputPass = Pass.getText();
try{
fileScan = new Scanner(new File(Inputuser + ".txt"));
filefound = true;
}
catch(FileNotFoundException ex){
JFrame FailureFrame = new JFrame("Something went wrong...");
JOptionPane.showMessageDialog(FailureFrame, "The username you have entered does not exist in our records. Please try again");
filefound=false;
}
//If the file was found (username exists)
if (filefound==true){
//Loops while the username while has more lines of content
while(fileScan.hasNext()){
lineVar = fileScan.next();
//Each line is considered a token
passwordScan = new Scanner(lineVar);
passwordScan.useDelimiter("/n");
while (passwordScan.hasNext()){
lineCount +=1;
if (lineCount == 2){
if (InputPass.equals( passwordScan.next() ) ){
JFrame successframe = new JFrame("Success!");
JOptionPane.showMessageDialog(successframe, "Login Successful!");
frame.dispose();
new MainProfile();
}
//If the password they entered is wrong
else{
JFrame notLogin = new JFrame ("Something went wrong...");
JOptionPane.showMessageDialog(notLogin, "You have entered invalid info. Please try again");
CompEnable();
}
}
}
}
}
}
}
答案 0 :(得分:3)
下面有一些提示可指导您解决问题:
检查while循环,它似乎阻止了Event Dispatching Thread(a.k.a。EDT)并冻结了你的GUI。另请查看Concurrency in Swing曲目,了解有关EDT如何工作以及如何处理它的更多详细信息。
您应该避免使用多个JFrame并考虑使用模态JDialog代替:How to Use Modality in Dialogs。另请查看此主题:The Use of Multiple JFrames, Good/Bad Practice?
您可能希望尝试Properties来存储用户密码,并使用Scanner类来摆脱处理文件的IO。 注意:理想情况下应该在数据库中完成,但在这种情况下,您在“.txt”文件中执行此操作,因此我认为属性更合适。请查看this trail和How to use Java property files?以了解属性。
<强>题外话:强>