从GUI读取文本文件

时间:2014-09-08 02:32:11

标签: java swing file-io

我有一个验证用户名和密码的GUI。赋值的另一部分是从包含用户名和密码的文件中读取,并检查它是否与用户在文本字段中放置的内容相匹配。如果它匹配则会隐藏登录页面,另一个页面将显示为"欢迎"信息。我没有文本文件的经验,我在哪里放置那段代码?我假设它会进入ActionListener方法,而不是主要方法,但我只是输了。我只需要朝着正确的方向努力。这是我到目前为止所拥有的。任何帮助将不胜感激。谢谢!

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
   private static final int FIELD_WIDTH = 10;
   private static final int FRAME_WIDTH = 500;
   private static final int FRAME_HEIGHT = 300;
   private JLabel fileRead;
   private JLabel instruct;
   private JLabel username;
   private JLabel password;
   private JTextField usertext;
   private JTextField passtext;
   private JButton login;
   private ActionListener listener;
   //String text = "";

   public PassWordFrame()
   {
      createComponents();
      setSize(FRAME_WIDTH, FRAME_HEIGHT);
      listener = new ClickListener();
   }
   class ClickListener implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
          String inputFileName = ("users.txt");
          File userFile = new File(inputFileName);

      }
   }
   public void createComponents()
   {
      Color blue = new Color(0,128,155);
      Font font = new Font("Times New Roman", Font.BOLD, 14);

      instruct = new JLabel("Please enter your username and password.");
      instruct.setFont(font);

      username = new JLabel("Username: ");
      username.setFont(font);

      password = new JLabel("Password: ");
      password.setFont(font);

      usertext = new JTextField(FIELD_WIDTH);
      passtext = new JTextField(FIELD_WIDTH);

      login = new JButton("Login");
      login.setFont(font);

      instruct.setForeground(Color.BLACK);
      login.setForeground(Color.BLACK);
      username.setForeground(Color.BLACK);
      password.setForeground(Color.BLACK);

      login.addActionListener(listener);

      JPanel panel1 = new JPanel();
      JPanel panel2 = new JPanel();
      JPanel panel3 = new JPanel();
      JPanel panel4 = new JPanel();

      panel1.setBackground(blue);
      panel2.setBackground(blue);
      panel3.setBackground(blue);
      panel4.setBackground(blue);

      panel1.add(instruct);
      panel2.add(username);
      panel2.add(usertext);
      panel3.add(password);
      panel3.add(passtext);
      panel4.add(login);

      add(panel1, BorderLayout.NORTH);
      add(panel2, BorderLayout.WEST);
      add(panel3, BorderLayout.CENTER);
      add(panel4, BorderLayout.SOUTH);

      pack();
   }
}      

import javax.swing.*;
import java.awt.*;

/**

*/
public class PassWordFrameViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new PassWordFrame();
      frame.setTitle("Password Verification");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

   }
}      

2 个答案:

答案 0 :(得分:2)

首先,在调用listener = new ClickListener()方法之后初始化侦听器(#createComponents()),这意味着您将向登录按钮添加null侦听器。所以你的构造函数应该是这样的:

    public PassWordFrame() {
      listener = new ClickListener();
      createComponents();
      setSize(FRAME_WIDTH, FRAME_HEIGHT);
    }

然后,因为您想要使用欢迎消息更改GUI,您应该使用SwingWorker,这是一个用于在后台线程中执行GUI交互任务的类。在javadoc中你可以找到很好的例子,但这里也是一个很好的教程:Worker Threads and SwingWorker

下面我只写你的监听器实现(使用swing工作者):

    class ClickListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {

        new SwingWorker<Boolean, Void>() {

          @Override
          protected Boolean doInBackground() throws Exception {

            String inputFileName = ("users.txt");
            File userFile = new File(inputFileName);

            BufferedReader reader = new BufferedReader(new FileReader(userFile));

            String user;
            String pass;

            try {
              user = reader.readLine();
              pass = reader.readLine();
            }

            catch (IOException e) {

              //
              // in case something is wrong with the file or his contents
              // consider login failed

              user = null;
              pass = null;

              //
              // log the exception

              e.printStackTrace();
            }

            finally {
              try {
                reader.close();
              } catch (IOException e) {
                // ignore, nothing to do any more
              }
            }

            if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
              return true;
            } else {
              return false;
            }
          }

          @Override
          protected void done() {

            boolean match;

            try {
              match = get();
            }

            //
            // this is a learning example so
            // mark as not matching
            // and print exception to the standard error stream

            catch (InterruptedException | ExecutionException e) {
              match = false;
              e.printStackTrace();
            }

            if (match) {
              // show another page with a "Welcome" message
            }
          }
        }.execute();
      }
    }

另一个提示:不要将组件添加到JFrame中,因此请将其替换为:

    add(panel1, BorderLayout.NORTH);
    add(panel2, BorderLayout.WEST);
    add(panel3, BorderLayout.CENTER);
    add(panel4, BorderLayout.SOUTH);

使用:

    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.add(panel1, BorderLayout.NORTH);
    contentPane.add(panel2, BorderLayout.WEST);
    contentPane.add(panel3, BorderLayout.CENTER);
    contentPane.add(panel4, BorderLayout.SOUTH);

    setContentPane(contentPane);

答案 1 :(得分:1)

假设g驱动程序中有一个名为password.txt的文本文件,它包含用@符号分隔的用户名和密码。

喜欢以下

password@123

示例代码

package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;

public class PassWordFrame extends JFrame
{
   private static final int FIELD_WIDTH = 10;
   private static final int FRAME_WIDTH = 500;
   private static final int FRAME_HEIGHT = 300;
   private JLabel fileRead;
   private JLabel instruct;
   private JLabel username;
   private JLabel password;
   private JTextField usertext;
   private JTextField passtext;
   private JButton login;
   private ActionListener listener;
   //String text = "";

   public PassWordFrame()
   {
      createComponents();
      setSize(FRAME_WIDTH, FRAME_HEIGHT);
      login.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                String info = ReadFile();
                System.out.println(info);
                String[] split = info.split("@");
                String uname=split[0];
                String pass =split[1];
                if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
                    instruct.setText("access granted");
                }else{
                    instruct.setText("access denided");
                }
            }
        }); 

   }
   private static  String ReadFile(){
        String line=null;
        String text="";
        try{

            FileReader filereader=new FileReader(new File("G:\\password.txt"));
             //FileReader filereader=new FileReader(new File(path));
            BufferedReader bf=new BufferedReader(filereader);
            while((line=bf.readLine()) !=null){
                text=text+line;

            }
            bf.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return text;

    }


   public void createComponents()
   {
      Color blue = new Color(0,128,155);
      Font font = new Font("Times New Roman", Font.BOLD, 14);

      instruct = new JLabel("Please enter your username and password.");
      instruct.setFont(font);

      username = new JLabel("Username: ");
      username.setFont(font);

      password = new JLabel("Password: ");
      password.setFont(font);

      usertext = new JTextField(FIELD_WIDTH);
      passtext = new JTextField(FIELD_WIDTH);

      login = new JButton("Login");
      login.setFont(font);

      instruct.setForeground(Color.BLACK);
      login.setForeground(Color.BLACK);
      username.setForeground(Color.BLACK);
      password.setForeground(Color.BLACK);

      login.addActionListener(listener);

      JPanel panel1 = new JPanel();
      JPanel panel2 = new JPanel();
      JPanel panel3 = new JPanel();
      JPanel panel4 = new JPanel();

      panel1.setBackground(blue);
      panel2.setBackground(blue);
      panel3.setBackground(blue);
      panel4.setBackground(blue);

      panel1.add(instruct);
      panel2.add(username);
      panel2.add(usertext);
      panel3.add(password);
      panel3.add(passtext);
      panel4.add(login);

      add(panel1, BorderLayout.NORTH);
      add(panel2, BorderLayout.WEST);
      add(panel3, BorderLayout.CENTER);
      add(panel4, BorderLayout.SOUTH);

      pack();
   }
}