Dustin
Dustin

Reputation: 185

Reading text file from a GUI

I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!

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

   }
}      

Upvotes: 2

Views: 3560

Answers (2)

Cristian Sulea
Cristian Sulea

Reputation: 264

First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:

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

Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.

Below i write you only the listener implementation (using a swing worker):

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

Another tip: don't add components to a JFrame, so replace this:

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

with:

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

Upvotes: 2

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9872

assume there is a textfile named password.txt in g driver and it contain usename and password separate by @ symbol.

like following

password@123

example code

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

Upvotes: 1

Related Questions