• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 903
  • Last Modified:

Validating a UserID and Password to Link up

Hello,

I was wondering if someone could help me.  I recently have been working an a program to allow a login to an application once the userID/name and password to inputed and "linked up", and therefore the need to validate the username/password.  

Previously i was using a web based program.  I have recently discovered that i can simply use an application instead of the web.  

So my question is how do i set up my validating user method to allow the user to input a username and password and for them to be stored in an array?

The code i have been working in is below:  THANKS FOR ANY AND ALL HELP.

Brooke

// Fig. 13.7: TextFieldTest.java
// Demonstrating the JTextField class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextFieldTest extends JFrame {
   private JTextField textField ;
   private JPasswordField passwordField;

   // set up GUI
   public TextFieldTest()
   {
      super( "Testing JTextField and JPasswordField" );

      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // construct textfield with default sizing
      textField1 = new JTextField( 10 );
      container.add( textField );

     
      // construct passwordfield with default text
      passwordField = new JPasswordField( "Hidden text" );
      container.add( passwordField );

      // register event handlers
      TextFieldHandler handler = new TextFieldHandler();
      textField.addActionListener( handler );
      passwordField.addActionListener( handler );

      setSize( 325, 100 );
      setVisible( true );

   } // end constructor TextFieldTest

  //added method to validate textfield username w/ corresponding password
     private class validateUser(String passwordField, String textField) {
   
     for( int i=0; i<TextFieldTest; i++ )
   {
       if ( textField.actionPerformed( textField ) && passwordField.actionPerformed( passwordField ) )
                   return true;
   }  
   public static void main( String args[] )
   {
      TextFieldTest application = new TextFieldTest();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }
     
  return false;
}
   // private inner class for event handling
   private class TextFieldHandler implements ActionListener {

      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = "";

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField )
            string = "Username " + event.getActionCommand();

         // user pressed Enter in JTextField passwordField
         else if ( event.getSource() == passwordField ) {
            string = "Password " +
               new String( passwordField.getPassword() );
         }

         JOptionPane.showMessageDialog( null, string );

      } // end method actionPerformed

   } // end private inner class TextFieldHandler

} // end class TextFieldTest

0
BrookeL
Asked:
BrookeL
  • 19
  • 13
  • 6
1 Solution
 
CEHJCommented:
You just need to add a button to your gui with that ActionListener added to the button. One way of handling 'post validation' would be to reveal another input form on validation - possibly using a JTabbedPane or a CardLayout
0
 
BrookeLAuthor Commented:
Do i keep my validateUser method, or should i delete it entirely and add the ActionListener button within the class TextFieldHandler?

I've never heard of JTabbedPane or CardLayout so i'll have to look into those suggestions, thanks very much though for your feedback.

B
0
 
suprapto45Commented:
Hi Brooke L,

Can you tell me more on your problem? I can't fully understand. I am sorry :)

Regards
Dave
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
>> Do i keep my validateUser method, or should i delete it entirely

You can just add the TextFieldHandler to the button.

>>'ve never heard of JTabbedPane or CardLayout so i'll have to look into those suggestions

The second is probably better:

http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
0
 
BrookeLAuthor Commented:
I'll try to add teh TextFieldHandler to the button later this evening.

Again, my goal is to create a method which will link up a username and password together as a pair, when they are entered by a user at login.

I was thinking that it's a double array.
such as
String username = [20]
String password =[20]
I need a method which stores the entered username/password together as in a "linked list" perhaps or "arrays".  I'm trying to allow a program to have a login function without using a database.  I know i have to create two strings and set them to some value.  However, if you look at my method:
private class validateUser i'm not sure if i have it placed in the correct part of the code nor am i sure if i should have created a for loop using TextFieldTest, as well as an if statement i created i'm not sure that is the correct syntax with variables and calls.

Thanks though.

Brooke
0
 
CEHJCommented:
Why do you need to store the entered uname and password? Surely you should be storing the correct pair and then checking the entered pair against it?
0
 
suprapto45Commented:
Oh,

I think that you need to have a kind of multidimension array like

String usernamepassw[][] = new String[20][2];

So
usernamepassw[0][0] = "david"; // username
usernamepassw[0][1] = "davidpassw"; // password

usernamepassw[1][0] = "brooke"; // username
usernamepassw[1][1] = "brookepassw"; // password

Does that what you want?

regards
Dave
0
 
BrookeLAuthor Commented:
Hi everyone

Thanks again for all your help, i have included the code for the user login.

Once again my goal of this project is to have the user enter their username and password.  The username and password will then be stored using a data structure(array/strings).  I have added a class Users as well as a method validateUser with parameters usr and pwd.  The for loop should create the array locations, if i am understanding the logic correctly as well as determine whether the array locations are linked up:
userCheck[0]=Brooke
userCheck[0]=1234

so for that entry the stored user name and password would be

username Brooke      
password 1234

Unfortunately i am able to compile and execute without any errors however, if you run the code the program doesn't seem to be storing the information together.  

I'm wondering if i should create an output of the two strings to show that they are linked(of course this would be for my own understanding of how this all works)

Basically i belieave i've followed all teh suggestions but it still doesn't seem to store the entered info.

Is this because i need to delete the actionPerformed method which displays the username and password individually once the enter key is pressed.  

Please check it out and give and suggestions or feedback on my goal of this code.

THANKS
BROOKE

CODE:

/*Purpose:  To allow the user to input their desired username and password
 *which will be stored in a data structure for later use; for instance when
 *the user wants to use the application again their username and password
 *will be assigned the same/linking locations, hence they will be validated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextFieldTest extends JFrame {
   private JTextField userName;
   private JPasswordField password;
   private JLabel textFieldLabel, passwordFieldLabel;
   private String userCheck[] = new String[10];
   private String passCheck[] = new String[10];
   
   // set up GUI
   public TextFieldTest()
   {
      super( "Please Login to AutoSync" );

      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // construct textfield with default sizing
      userName = new JTextField( 10 );
      //creating textfield label
      textFieldLabel = new JLabel("Username");
      container.add(textFieldLabel);
      container.add( userName);

      // construct passwordfield with default text
      password = new JPasswordField( "Hidden text" );
      passwordFieldLabel = new JLabel("Password");
      container.add(passwordFieldLabel);
      container.add( password );

      // register event handlers
      TextFieldHandler handler = new TextFieldHandler();
      userName.addActionListener( handler );
      password.addActionListener( handler );

      setSize( 325, 100 );
      setVisible( true );          
   
   } // end constructor TextFieldTest

   public static void main( String args[] )
   {
      TextFieldTest application = new TextFieldTest();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

   // private inner class for event handling
   private class TextFieldHandler implements ActionListener {

      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = "";

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == userName )
            string = "userName: " + event.getActionCommand();

         // user pressed Enter in JTextField passwordField
         else if ( event.getSource() == password ) {
            string = "password: " +
               new String( password.getPassword() );
         }

         JOptionPane.showMessageDialog( null, string );

      } // end method actionPerformed

   } // end private inner class TextFieldHandler
   
   //private class users to link username/password input with Array locations
   private class Users{
   
   private boolean validateUser(String usr, String pwd) {
       
        for (int i = 0; i < userCheck.length; i++)
    {
        if (userCheck[i].equals(usr) && passCheck[i].equals(pwd))
        {
              return true;              
        }
    }
                 return false;

     }     //end method validateUser

   }     //end class users

} // end class TextFieldTest}


 
 
   

 
 
0
 
suprapto45Commented:
Hi,

>>"Once again my goal of this project is to have the user enter their username and password.  The username and password will then be stored using a data structure(array/strings). "

What do you mean by that? If I am not mistaken, you want to allow the user to enter their username and password. The system would then save this information in a kind of array for future purposes. If so, you should start to consider the use of database to persistently store your data. Otherwise, after the application is closed, all the data will still be lost.

Please let me know if I wrongly understand you.

Regards
Dave
0
 
BrookeLAuthor Commented:
No Dave that's it exactly.  I thought that using arrays is a type of memory storage for data.  I was under the impression that algorithms essentially act as a database for storing data, that is why i choose the array approach.  As far as using a database i would rather avoid that.  I'm getting a little worried, am i approaching this completely wrong?  Once again, there isn't a way to store data unless you use databases?  
0
 
suprapto45Commented:
Hi Brooke,

Well, if you use to choose the Array approach, this is not the best way :(. Consider this.....after you save the username and password of 10 users. Then you close your application. Then, you run the application again.....the 10 users information will totally be lost unless you save it somewhere persistently (either to Database or text files).

Consider this.....
Perhaps, in your thought, we can hardcode the username and password as
String[] user = new String[2];
String[] passw = new String[2];

user[0] = "brooke";
passw[0] = "brooke";

user[1] = "david";
passw[1] = "david";

For that case, that would be okay....but it always limited to 2 users. Now, if you want to add the third user, you need to have one way to store the data for third person in somewhere and load this data into your application to validate the third person.

I hope that make things cleaner....but truly, the best way is to use database.

Regards
Dave
0
 
BrookeLAuthor Commented:
Thanks Dave for you suggestions.

I'm going to reference my data structures book, i belieave i remember seeing something in there on storing data in a text document and calling that text document in your source code.  I'll give that a try.

THANKS FOR ALL YOUR HELP

Brooke
0
 
suprapto45Commented:
No worries :)

Regards
Dave
0
 
CEHJCommented:
>>
i belieave i remember seeing something in there on storing data in a text document and calling that text document in your source code.
>>

I already mentioned how to implement this very simply for your username and password in one of your previous questions on exactly the same matter, but my comments were ignored
0
 
BrookeLAuthor Commented:
I couldn't find your comment on this before.  However i have been researching into this concept of creating a text file from user input as arrays.  

Question is should i be using both datainputStream and dataoutputstream in order to create the text file?  Also do i have to change the path on myJCreator for the file to be created?

Thanks for Any Help

Brooke
0
 
CEHJCommented:
>>
Easiest to just put the uname/password pairs in a properties file:

file:

admin=abracadabra
manager=hocuspocus


SNIP================================


Properties users = new Properties();
users.load(getClass().getResourceAsStream("users.properties"));

String password = null;
boolean authorised = false;
if ((password = users.getProperty(enteredUser)) != null) {
     authorised = enteredPassword.equals(password);
}
>>

( http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21408979.html )

>>Question is should i be using both datainputStream and dataoutputstream in order to create the text file?

No text files should be manipulated using Reader and Writer. You can make an exception for reading a properties file - you use an InputStream as Reader is not supported
0
 
BrookeLAuthor Commented:
Thanks I'm working/trying to write the code now.

Brooke
0
 
BrookeLAuthor Commented:
Code actually doesn't work, but i was thinking that where i have brooke
        //if i should create another actionlistner to combine the userName and password
        //inputs into one field, perhaps a login button which hold both those arrays
        //then i can do writer.write("combinedfields")

Please excuse my lack of terminology

What is happening when i run the application: i get no errors and no stored text file in notepad, when i run

class WriteTextFile
{

  public static void main ( String[] args ) throws IOException
  {
    String fileName = "Senior.txt" ;

    FileWriter writer = new FileWriter( fileName );

    writer.write( "Brooke,\n"  );  
   
    writer.close();
  }
}
I AM ABLE TO GENERATE A TEXT FILE NAMED SENIOR WITH THE DATA BROOKE INSIDE THE FILE.
so i'm thinking
1. am i supposed to create another java file to hold the class FileWriter
2.I tried to implement my example my FileWriter into my TextFieldTest driver/main but i recieved errors
perhaps this is becasue i still haven't assigned my userName input and password inputs as one string of characters?



/*Purpose:  To allow the user to input their desired username and password
 *which will be stored in a data structure for later use; for instance when
 *the user wants to use the application again their username and password
 *will be assigned the same/linking locations, hence they will be validated.
 *inputed username and password should be stored in a text field for later use
 *of validating login possbily using a search method
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.lang.String.*;

public class TextFieldTest extends JFrame {
   private JTextField userName;
   private JPasswordField password;
   private JLabel textFieldLabel, passwordFieldLabel;

   
   
   // set up GUI
   public TextFieldTest()
   {
      super( "Please Login to AutoSync" );

      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // construct textfield with default sizing
      userName = new JTextField( 10 );
      //creating textfield label
      textFieldLabel = new JLabel("Username");
      container.add(textFieldLabel);
      container.add( userName);

      // construct passwordfield with default text
      password = new JPasswordField( "Hidden text" );
      passwordFieldLabel = new JLabel("Password");
      container.add(passwordFieldLabel);
      container.add( password );

      // register event handlers
      TextFieldHandler handler = new TextFieldHandler();
      userName.addActionListener( handler );
      password.addActionListener( handler );

      setSize( 325, 100 );
      setVisible( true );
     
   }// end constructor TextFieldTest
   
//ADDED TO CREATE TEXT FILE OF USER INPUTS
   //Code actually doesn't work, but i was thinking that where i have brooke
        //if i should create another actionlistner to combine the userName and password
        //inputs into one field, perhaps a login button which hold both those arrays
        //then i can do writer.write("combinedfields")
        
   public class FileWriter{
         
          String fileName = "SENIOR.txt" ;
          
          writer.write( "Brooke,\n"  );  
   
    writer.close();
         
   }
   public static void main( String args[] )throws IOException
   {  
 
            //ADDED FOR OUTPUTTING TO TEXT FILE, FILEWRITER
    FileWriter writer = new FileWriter( fileName );    
   
      TextFieldTest application = new TextFieldTest();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

   // private inner class for event handling
   private class TextFieldHandler implements ActionListener {

      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = "";

         // user pressed Enter in JTextField textField1
         if ( event.getSource() == userName )
            string = "userName: " + event.getActionCommand();

         // user pressed Enter in JTextField passwordField
         else if ( event.getSource() == password ) {
            string = "password: " +
               new String( password.getPassword() );
         }

         JOptionPane.showMessageDialog( null, string );

      } // end method actionPerformed

   } // end private inner class TextFieldHandler
   
 
   //private class users to link username/password input with Array locations
   private class Users{
               public String userCheck[] = new String[10];       
               public String passCheck[] = new String[10];      
            
   private boolean validateUser(String usr, String pwd)throws IOException {
               
         
         for (int i = 0; i < userCheck.length; i++)
    {
        if (userCheck[i].equals(usr) && passCheck[i].equals(pwd))
        {
              return true;              
        }
    }
                    return false;
                    
 

      }      //end method validateUser

   }      //end class users
   
} // end class TextFieldTest}

0
 
BrookeLAuthor Commented:
I'm thinking i should concatenate the userName and password objects into one object string, then i can send that string of concatenation to the text file for searching later.  

CEHJ and Dave does that make sense?  I realized that i don't have a login button on my application, and that it appears it would be easier to have a login button that the user clicks on, which concatenates the two objects(userName and password) into one object string say Data.  Then data is stored into the text file.

The way i have it set up the two fields for password and userName are not linking and upon execution they just will display the input of each individual field---There isn't a concatenation occuring.  

Does my train of thought make any sense.

I know you suggested the properties file but i'm still working on linking the fields as one string of characters to be stored in teh text file.

Thanks again in advance for feedback

Brooke
0
 
BrookeLAuthor Commented:
YES!!!!!

OK so i figured out how to generate the text file and also run the application.

I'm working on concatenating the fields userName and password into one string for exporting into the text file.

my driver looks as follows.  It allows the main class TextFieldTest to run as well as generating the text file data.txt(however no data is loaded in it yet--working on that)

 public static void main( String args[] )throws IOException
   {           
     String fileName = "data.txt";
     FileWriter writer = new FileWriter(fileName);
     writer.write("Brooke");
    TextFieldTest1 application = new TextFieldTest1();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   
   }

I'm thinking i need to write the method write() with a bufferedReader as teh input stream from the user for both the userName and password fields.

Hope i'm approaching this correctly.

Thanks for any help
Brooke
0
 
CEHJCommented:
There seems top be a lack of clarity about what your app should be doing - certainly i'm confused about it ;-) Perhaps before you go any further you should clarify this, *using non-technical language*. E.g.

1. I want the user to fill in their username and password in a box
2. The user clicks a button
3. The app authorises them as a valid user (or not)
0
 
BrookeLAuthor Commented:
Yes that's it exactly..
0
 
BrookeLAuthor Commented:
So check this out i added a string which concatenates the inputed userName and password as one string to be exported into the external document.  This is what i mean:

inputed userName = Brooke
inputed password = apple
String string = Brookeapple to be input into the external document.

I put the concatenation in my driver, please by attention to the driver(main).
Thanks Any help is appreciated.

Brooke

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.lang.String.*;

public class TextFieldTest2 extends JFrame {
   private JTextField userName;
   private JPasswordField password;
   private JLabel textFieldLabel, passwordFieldLabel;  
   // set up GUI
   public TextFieldTest2()
   {
      super( "Please Login to AutoSync" );

      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // construct textfield with default sizing
      userName = new JTextField( 10 );
      //creating textfield label
      textFieldLabel = new JLabel("Username");
      container.add(textFieldLabel);
      container.add( userName);

      // construct passwordfield with default text
      password = new JPasswordField( "Hidden text" );
      passwordFieldLabel = new JLabel("Password");
      container.add(passwordFieldLabel);
      container.add( password );

      // register event handlers
      TextFieldHandler handler = new TextFieldHandler();
      userName.addActionListener( handler );
      password.addActionListener( handler );

      setSize( 325, 100 );
      setVisible( true );
     
   }// end constructor TextFieldTest
     
   public static void main( String args[] )throws IOException{           
                 //creating string to combine userName and password inputs
     String string = "userName: " + userName.getText() + "password: "  + password.getText();

      //creating external text file named ITWORKS
     String fileName = "ITWORKS.txt";
     FileWriter writer = new FileWriter(fileName);      
              //SUPPOSED TO LOAD DATA OF string INTO TEXT FILE
     writer.write(string);         //string=concatenated userName+password
     writer.close();
     
    TextFieldTest2 application = new TextFieldTest2();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );  
   }
   // private inner class for event handling
   private class TextFieldHandler implements ActionListener {

      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
                  String string = "";
         // user pressed Enter in JTextField textField1
         if ( event.getSource() == userName )
            string = "userName: " + event.getActionCommand();

         // user pressed Enter in JTextField passwordField
         else if ( event.getSource() == password )
            string = "password: " +
               new String( password.getPassword() );        

         JOptionPane.showMessageDialog( null, string );

      } // end method actionPerformed

   } // end private inner class TextFieldHandler
   
   //private class users to link username/password input with Array locations
   private class Users{
             public String userCheck[] = new String[10];      
             public String passCheck[] = new String[10];    

   
   //private class validateUser to link username/password input with Array locations             
   private boolean validateUser(String usr, String pwd)throws IOException {
                        
         for (int i = 0; i < userCheck.length; i++)
          {
        if (userCheck[i].equals(usr) && passCheck[i].equals(pwd))
              {
              return true;              
              }
          }
                    return false;
              }//end validateUser
        
      }      //end method Users
        
} // end class TextFieldTest

ERRORS I"M GETTING ARE

D:\DataDocument\TextFieldTest2.java:49: non-static variable userName cannot be referenced from a static context
     String string = "userName: " + userName.getText() + "password: " 
                                    ^
D:\DataDocument\TextFieldTest2.java:50: non-static variable password cannot be referenced from a static context
         + password.getText();
           ^
Note: D:\DataDocument\TextFieldTest2.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
2 errors

Process completed.
0
 
CEHJCommented:
>>So check this out i added a string which concatenates the inputed userName and password as one string to be exported into the external document.

None of that functionality appears in 'my summary' of your required functionality, which you described as:

>> it exactly..
0
 
BrookeLAuthor Commented:
i haven't added the button yet.  I should of done that first.  My mistake.

Once the login button is pressed(which i need to add) the two strings userName and password should be concatenated and sent to teh external document.

In your opinion, should i not even bother with concatenating, is there an easier way of loading the data in the external document that you're aware of?  I"m not at all familiar with the properties suggestion, but if that is easier to implement i'd rather attempt that.  What do you think?

Thanks

Brooke
0
 
CEHJCommented:
Since there is not mention of external documents in my summary, please follow my original suggestion:

>>
There seems top be a lack of clarity about what your app should be doing - certainly i'm confused about it ;-) Perhaps before you go any further you should clarify this, *using non-technical language*
>>

0
 
BrookeLAuthor Commented:
I'm sorry for being confusing and thanks for being patient with me.

Application Goal:
1.User enters in their username and password
2.They press the enter key(not going to use the button idea anymore)
2.Username and password are stored in document(notepad file), so that next time that try to login thier information can be located/verified off of the notepad document.
(i'm trying to create a login code so that each time some wants to use my software, they must login in and be verified with thier already stored inputed username and password)
3.User at next attempt to use software will be prompted for login.
4.If their login is correct and matches the stored username password that they gave previously they will have access.
5.Login verified or denied

HOPE THAT HELPS--i tend to be a little wordly.

1.enter username and password at 1st login
2.enter username and password at 2nd login session
3."THE user" is then either granted access or not, depending on the validity of thier input and whether it matches thier previously stored username and password(stored in docuement(notepad))

THANKS
BROOKE
0
 
suprapto45Commented:
Hi Brooke,

Sorry....I was extremely busy. I hope that CEHJ has solved your question.

>>"Once the login button is pressed(which i need to add) the two strings userName and password should be concatenated and sent to teh external document."
As you said that there is no need for button, so when you save the username and password, you do not need to concatenate them. You can store them in Comma Separated values (CSV) file to ease you in retrieving the data.

Such as:
Test.csv
brooke,brookepassw
david,davidpassw
cehj,cehjpassw

Regards
Dave
0
 
BrookeLAuthor Commented:
Thanks Dave

I"m gonna give that a whirl tomorrow....I'll let you know the outcome

Thanks Again in

Brooke
0
 
CEHJCommented:
You can also write the properties too:

Properties props = new Properties();
String password = null;
if ((password = props.getProperty(candidateUsername)) == null) {
    // New user - create it and save it
    props.setProperty(candidateUsername, candidatePassword);
    props.store(new FileOutputStream("users.properties"), "Users");
}
else if (password.equals(candidatePassword)) {
    // Valid user
}

What you'll have to watch out for here (constructed from your 'application goal') is the fact that this will allow *any* login since it effectively says 'save any entered username and password combination' which is probably undesirable
0
 
BrookeLAuthor Commented:
Need a little clarification.

I'm supposed to create another class named Properties with the method props(), is that correct?


Thanks

Brooke

0
 
CEHJCommented:
>>I'm supposed to create another class named Properties with the method props(), is that correct?

No, you're supposed to create a class of *type* Properties (java.util.Properties) named 'props' (the variable name). There is no props() method.
0
 
CEHJCommented:
Here are some more examples (link at bottom too) of using Properties:

http://javaalmanac.com/egs/java.util/Props.html
0
 
BrookeLAuthor Commented:
I have a couple questions, if you don't mind....


So i've been working on implementing the props class. i have props declared as private Properties props;

i added the class and am importing the necessary packages, but am still recieving an error as illegal start of expression.

So this is my train of thought:

1. I no longer need FileWriter or fileName since i will be creating a properties file, therefore i removed those code segments from my main driver.

2.I also removed my entire private class TextFieldHandler including the method actionPerformed, my reasoning for this is that that class creates outputs for the textfields individually.  

3.i need to now create a actionlistener for a textfieldhandler of a login button.

Does this seem correct?

Thanks

Brooke
0
 
BrookeLAuthor Commented:
I decided to keep the TextFieldHandlers and actionPerformed, but i have added a button and the private class props.
I keep getting an error at my if statement
:\DataDocument\TextFieldTest3.java:149: illegal start of type
        if ((password = props.getProperty(userName)) == null) {
        ^
D:\DataDocument\TextFieldTest3.java:160: <identifier> expected
                }//end else if    
                  ^

/*Purpose:To have a user input their username and password which is to be stored
 *in a string to be stored into an external file for validating thier inputs
 *next time application is run.  Essentially a login application.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.lang.String.*;

public class TextFieldTest3 extends JFrame {
   private JTextField userName;
   private JPasswordField password;
   private JLabel textFieldLabel, passwordFieldLabel;
    private JButton loginButton;
 
 
   // set up GUI
   public TextFieldTest3()
   {
      super( "Please Login to AutoSync" );

      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // construct textfield with default sizing
      userName = new JTextField( 10 );
      //creating textfield label
      textFieldLabel = new JLabel("Username");
      container.add(textFieldLabel);
      container.add( userName);

      // construct passwordfield with default text
      password = new JPasswordField( "Hidden text" );
      passwordFieldLabel = new JLabel("Password");
      container.add(passwordFieldLabel);
      container.add( password );
     
      // register event handlers
      TextFieldHandler handler = new TextFieldHandler();
      userName.addActionListener( handler );
      password.addActionListener( handler );

      //creating loginButton
      loginButton = new JButton("Login");
      container.add(loginButton);  
       
      //creating instance for button handler
      ButtonHandler handler1 = new ButtonHandler();
       loginButton.addActionListener(handler1);
       
       handler1.addActionListener(
       
                         new ActionListener(){
                               public void actionPerformed(ActionEvent event)
                               {
                                     Object value = props.setProperty(
                                           userName.getText(), password.getText());
                                           if(value ==null)
                                           showstatus("UserName" + userName.getText() +
                                           "" + password.getText());
                                           else
                                                 showstatus("Password:" + userName.getText()+
                                                 ""+password.getText() + ";login" + value);
                                                 listProperties();
                                     }            
                               }//end inner clas ActionListener                   
                         );

     
      setSize( 325, 100 );
      setVisible( true );
     
   }// end constructor TextFieldTest
     
   public static void main( String args[] )throws IOException{           
     
      //creating external text file named ITWORKS
     String fileName = "DATAofUSERS.txt";
     FileWriter writer = new FileWriter(fileName);      
     //SUPPOSED TO LOAD DATA OF string INTO TEXT FILE
     writer.write("ROY ORBISON hardcoded ");//string=concatenated userName+password
     writer.close();
     
     
     
    TextFieldTest3 application = new TextFieldTest3();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );  
   }
   // private inner class for event handling
   private class TextFieldHandler implements ActionListener {

      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
            
            String string = "";
                  
      // user pressed Enter in JTextField textField1
               if (event.getSource()==userName)        
            string = "userName: " + event.getActionCommand();

         // user pressed Enter in JTextField passwordField
            string = "password: " +
               new String( password.getPassword() );
                       

        JOptionPane.showMessageDialog( null, string );

      } // end method actionPerformed

   } // end private inner class TextFieldHandler
   
    private class ButtonHandler implements ActionListener{
         
         public void actionPerformed(ActionEvent event)
         {      
               JOptionPane.showMessageDialog(TextFieldTest3.this, "Successful" + event.getActionCommand());
         }
   }
   
   //private class users to link username/password input with Array locations
   private class Users{
             public String userCheck[] = new String[10];      
             public String passCheck[] = new String[10];    

   
   //private class validateUser to link username/password input with Array locations             
   private boolean validateUser(String usr, String pwd)throws IOException {
                        
         for (int i = 0; i < userCheck.length; i++)
          {
        if (userCheck[i].equals(usr) && passCheck[i].equals(pwd))
              {
              return true;              
              }
          }
                    return false;
              }//end validateUser
        
      }      //end method Users
      
      private class props extends JFrame {
            
            Properties props = new Properties();
      String password = null;
      
      if ((password = props.getProperty(userName)) == null) {
    // New user - create it and save it
    props.setProperty(userName, password);
    props.store(new FileOutputStream("users.properties"), "Users");
   
      }
      else if (password.equals(password)) {
    // Valid user
    props.setProperty(userName,password);
    props.store(new FileOutputStream("users.properties"), "Users");
            
            }//end else if    
      }//end class props
        
} // end class TextFieldTest

Am i approaching this wrong, again??

Thanks for any feedback, once again.

Brooke


0
 
CEHJCommented:
The area around

>>private class props extends JFrame

is wrong. You need to use a Properties class. There's no need to extend another class, let alone JFrame. Just let the main class own the Properties object. I would have a writePassword and readPassword method
0
 
BrookeLAuthor Commented:
Thanks Cehj so much for your help

So my deadline for my project has come and gone...i wanted to award you the points even though i still wasn't able to load the data in the ext.document....i simply just ran out of time to try to implement your last suggestion...i due however plan to continue to work on it, for my own curiosity and desire to actually be able to complete/accomplish this new found goal of mine....thanks again

Brooke

---you explain things very well
0
 
CEHJCommented:
:-)

If you do any more work, post back here and i'll try to help
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 19
  • 13
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now