Java Swing记得密码

时间:2017-03-03 13:53:09

标签: java swing serialization

我想让用户/传递checkButton以保持用户并通过。因此,第一次打开应用程序并输入通行证和用户并选择rememberBox以保存此检查,之后我将再次打开以保持检查并且通行证和用户已经被写入。

这是代码:

JButton btnLogin = new JButton("Login");
Image ok = new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLogin.setIcon(new ImageIcon(ok));
btnLogin.addActionListener(new ActionListener() {

    @SuppressWarnings("deprecation")

    public void actionPerformed(ActionEvent arg0) {
        String user = "marius";
        String password = "Amina1";  
        UPDATE();

        if(userName.getText().equals(user) && passwordField.getText().equals(password)){
             if(checkBox.isSelected()){
                  SAVE(); //Save This UserName and his PassWord     
               }

            window.frmUserpass.dispose();
            WelcomePage welcomePage = new WelcomePage();
            welcomePage.Screen1();
        }else {
            JOptionPane.showMessageDialog(btnLogin, "Introduceti unuser si o parola valida!", "Error", 0);

            passwordField.selectAll();
        }
    }

    private void SAVE() {
        try {
            if(!file.exists()) file.createNewFile();  //if the file !exist create a new one
            BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
            bw.write(userName.getText()); //write the name
            bw.newLine(); //leave a new Line
            bw.write(passwordField.getPassword()); //write the password
            bw.close(); //close the BufferdWriter
        } catch (IOException e) { e.printStackTrace(); }    
    }

    private void UPDATE() {
         try {
              if(file.exists()){    //if this file exists
                Scanner scan = new Scanner(file);   //Use Scanner to read the File
                userName.setText(scan.nextLine());  //append the text to name field
                passwordField.setText(scan.nextLine()); //append the text to password field
                scan.close();
              }
            } catch (FileNotFoundException e) {         
                e.printStackTrace();
            }                
    }   
    });
btnLogin.setBounds(231, 112, 89, 23);
frmUserpass.getContentPane().add(btnLogin);

0 个答案:

没有答案