Java - 在GUI中从文件设置密码

时间:2014-09-18 02:45:53

标签: java swing file-io passwords jframe

我最近学会了如何使用NetBeans GUI编辑器,我真的很喜欢它,但我遇到了一个问题。我正在制作一个需要登录的个人使用程序。登录的密码是从文件中检索的,可以更改。到目前为止,制作文本文件,放置内容和更改内容不是问题。我的问题是将String密码设置为等于文本文件中的任何内容。请帮帮我。这是代码。 (jPasswordField1是密码框,jButton1是打开更改密码的菜单的按钮。)

package my.shortcutApp;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class shotcutApp extends javax.swing.JFrame
{
    File passwordFile = new File("C:/Program Files (x86)/Steam/userdata/193530500/7/remote/Game Data.txt");
    String password; // I need this to equal ^^
    String reset = "";
    public shotcutApp()
    {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        loginPanel = new javax.swing.JPanel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        loginPanel.setName("Organizer"); // NOI18N

        jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Login");

        jButton1.setText("change");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout loginPanelLayout = new javax.swing.GroupLayout(loginPanel);
        loginPanel.setLayout(loginPanelLayout);
        loginPanelLayout.setHorizontalGroup(
            loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginPanelLayout.createSequentialGroup()
                .addGap(128, 128, 128)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(loginPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(128, Short.MAX_VALUE))
        );
        loginPanelLayout.setVerticalGroup(
            loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loginPanelLayout.createSequentialGroup()
                .addContainerGap(259, Short.MAX_VALUE)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPasswordField1)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {                                                
        String input = evt.getActionCommand();
        if (input.equals(password))
        {
            loginPanel.setVisible(false);
        }
        else if (!input.equals(password))
        {
            JOptionPane.showMessageDialog(this, "Wrong password.");
        }
        jPasswordField1.setText("");
    }                                               

    @SuppressWarnings("ConvertToTryWithResources")
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        if (!passwordFile.exists())
        {
            reset = JOptionPane.showInputDialog("Please enter new password.");
            try {passwordFile.createNewFile();} catch (IOException ex) {Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);}
            try {
                BufferedWriter output = new BufferedWriter(new FileWriter(passwordFile));
                output.write(reset);
                output.close();
            } catch (IOException ex) {
                Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else if (passwordFile.exists())
        {
            reset = JOptionPane.showInputDialog("Please enter old password.");
            if (reset.equals(password))
            {
                try {PrintWriter pw = new PrintWriter(passwordFile);pw.close();} catch (FileNotFoundException ex) {Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);}
                password = JOptionPane.showInputDialog("Please enter new password.");
                try {
                    BufferedWriter output = new BufferedWriter(new FileWriter(passwordFile));
                    output.write(password);
                    output.close();
                } catch (IOException ex) {
                    Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else if (!reset.equals(password))
            {
                JOptionPane.showMessageDialog(this, "Wrong password.");
            }
        }
    }                                        

    public static void main(String args[])
    {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new shotcutApp().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPanel loginPanel;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

如果我确实理解了你,你实际上需要一个配置文件和读写属性。我为你做了一个请看。我在textfield中输入密码以显示正在发生的事情,稍后您可以将其更改为passwordfield。您还可以打开配置文件并进行更改并保存。您可以为配置文件指定任何名称。您可以在输入新密码时尽可能多地更改密码,然后按“保存”按钮,然后更新配置文件。

配置文件

enter image description here

enter image description here

创建类配置

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Configs {

    public static Properties prop = new Properties();

    public void SaveProp(String title, String value) {

        try {
            prop.setProperty(title, value);
            prop.store(new FileOutputStream("configuration.con"), null);

        } catch (IOException e) {

        }

    }

    public String GetProp(String title) {
        String value = "";

        try {

            prop.load(new FileInputStream("configuration.con"));
            value = prop.getProperty(title);

        } catch (IOException e) {

        }

        return value;
    }

}

登录类中的字段

Configs con = new Configs();
String UserName = "UserName";
String Password = "Password";
String newpassword;
String newuser;

执行保存按钮操作

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    con.SaveProp(UserName, jTextField1.getText());
    con.SaveProp(Password, jTextField2.getText());

}  

显示按钮操作

      private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

      newuser = con.GetProp("UserName");
      newpassword = con.GetProp("Password");
      jTextField3.setText(newuser);
      jTextField4.setText(newpassword);

}