【问题标题】:Java - setting password from file in GUIJava - 在 GUI 中从文件设置密码
【发布时间】:2014-09-18 02:45:52
【问题描述】:

我最近学会了如何使用 NetBeans GUI 编辑器,我真的很喜欢它,但是我遇到了一个问题。我正在制作一个需要登录的个人使用程序。登录密码是从文件中检索的,并且可以更改。到目前为止,制作文本文件、放置内容和更改内容都不是问题。我的问题是将字符串密码设置为等于文本文件中的任何内容。请帮帮我。这是代码。 (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                   
}

【问题讨论】:

  • 我的问题是将字符串密码设置为等于文本文件中的任何内容。你这是什么意思?请也发布您的文件内容
  • 你知道如何在 Java 中读取文件吗?
  • “我正在制作一个需要登录的个人使用程序。” 1) 如果是个人使用,我会硬编码密码。 2) 如果它实际上供他人使用,则不建议将密码存储在文本文件中。 3) 如果这是学习一点关于 Java I/O 的任意任务,我会这样说。

标签: java swing file-io passwords jframe


【解决方案1】:

如果我对您的理解正确,您实际上需要一个配置文件和其中的读写属性。我给你做了一个,请看。我在文本字段中设置了密码以向您展示发生了什么,您可以稍后将其更改为密码字段。您还可以打开配置文件并进行更改并保存。您可以为配置文件指定任何名称。您可以在输入新密码并按保存按钮时尽可能更改密码,然后配置文件将被更新。

配置文件

创建类配置

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);

}

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2016-09-28
    • 2011-03-19
    相关资源
    最近更新 更多