getText() vs getPassword() - java

I'm currently designing a login system for a make-believe company, right now all I have is the Main login, which needs a lot of cleaning up. Below is my login handler.
private class LoginButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(_uid.getText().equalsIgnoreCase("Nathan") && _pwd.getText().equals("password")) {
JOptionPane.showMessageDialog(null, "Congratulations on logging in!");
} else {
JOptionPane.showMessageDialog(null, "Error on login!");
}
}
}
As is, this works perfectly fine, but when I change it to
_pwd.getPassword.equals("password")
it directs straight to the else statement when everything is input correctly.
What is wrong here? Full program below.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame {
private static final int HEIGHT = 90;
private static final int WIDTH = 400;
JTextField _uid = new JTextField(10);
JPasswordField _pwd = new JPasswordField(10);
JButton _login = new JButton("Login");
JButton _reset = new JButton("Reset");
public Main() {
super("Login - Durptech");
Container pane = getContentPane();
setLayout(new FlowLayout());
add(new JLabel("User ID:"));
add(_uid);
add(new JLabel("Password:"));
add(_pwd);
add(_login);
_login.addActionListener(new LoginButtonHandler());
add(_reset);
_reset.addActionListener(new ResetButtonHandler());
/*if(_uid.getText().equals("") && _pwd.getText().equals("")) {
_login.setEnabled(false);
} else {
_login.setEnabled(true);
}*/
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocation(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class ResetButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
_uid.setText("");
_pwd.setText("");
_uid.requestFocusInWindow();
}
}
private class LoginButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(_uid.getText().equalsIgnoreCase("Nathan") && _pwd.getText().equals("password")) {
JOptionPane.showMessageDialog(null, "Congratulations on logging in!");
} else {
JOptionPane.showMessageDialog(null, "Error on login!");
}
}
}
public static void main(String[] args) {
new Main();
}
}

You will want to get to know the API well, to make it your best friend. The key to solving this is to see what JPasswordField#getPassword() returns. Hint 1: it's not a String. Hint 2: you may want to solve this using the java.util.Arrays class methods.
The reason getPassword doesn't return a String is because of the way Java handles Strings -- it can store them in the String pool, allowing Strings to hang out in the program longer than you'd expect, and making the Strings potentially retrievable by malware -- something you don't want to have happen to a password. It's much safer to work with char arrays.
Incidentally, don't use JPasswords deprecated getText() method or change a char array to a String using the new String(char[]) constructor since as these both return a String, they are not secure.

JPasswordField.getPassword() returns a char [] instead of a String. This is done for the sake of security. You should compare the characters inside the array instead of seeing if the char [] .equals(a String);

password.getPassword() returns a char[], and char[]'s aren't equal to Strings. So you need to compare it to a char[]:
if (Arrays.equals(password.getPassword(), new char[]{'p','a','s','s','w','o','r','d'}))

As all the other answers have said, JPasswordField returns a char[] when you call the getPassword() method. However, the way I have it set in my sample log on form is I have a method for validating the input. I have two arrays for storing usernames[] and passwords[] and then I have my username input, and my password input. The password input in my method changes the char[] to a string before continuing, you can do so like this:
String PasswordTyped = new String(_pwd.getPassword());
Then take that string and place that in your 'if' statement:
if (_uid.equals("Nathan") && PasswordTyped.equals("password") {
JOptionPane.showMessageDialog(null, "Congrats, you logged in as Nathan");
}
However, as I mentioned my validation method runs on the two arrays of usernames[] and passwords[], while accepting a string and a char[] as input. I will copy and paste my method so you can implicate it if you would like:
public static void validate(String u, Char[] pass) {
String password = new String(pass);
boolean uGood = false;
String[] usernames = new String[2];
String[] passwords = new String[usernames.length];
usernames[0] = "Don";
passwords[0] = "password";
usernames[1] = "Jared";
passwords[1] = "password";
for (int i = 0; i < usernames.length; i++) {
if (usernames[i].equals(u) && passwords[i].equals(password)) {
uGood = true;
}
}
if (uGood) {
System.out.println("Hooray, you did it!");
}
else {
JOptionPane.showMessageDialog(null, "Incorrect Username\nand/or Password.");
}
}
Finally, you would call this validation method by typing:
validate(_uid.getText(), _pwd.getPassword());

Related

How would I program an array of Strings to work as a set of passwords?

So I'm trying to get a java applet to accept a set of multiple passwords, so naturally I thought to put them in array. However, only one of the passwords in the array is working, the last one in the set. None of the ones before it will work and my applet denies the others. This is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JPasswordC extends JApplet implements ActionListener
{
private final String[] password = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
private Container con = getContentPane();
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField passwordField = new JTextField(16);
private JLabel grantedPrompt = new JLabel("<html><font color=\"green\">Access Granted</font></html>");
private JLabel deniedPrompt = new JLabel("<html><font color=\"red\">Access Denied</font></html>");
public void init()
{
con.setLayout(new FlowLayout());
con.add(passwordLabel);
con.add(passwordField);
con.add(grantedPrompt);
grantedPrompt.setVisible(false);
con.add(deniedPrompt);
deniedPrompt.setVisible(false);
passwordField.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String input = passwordField.getText();
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
}
else
{
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}
}
}
}
How would I get this to work properly? Am I doing something wrong with the array? Is it something in the code altogether?
The code is checking each password even if a valid one is found meaning that even if a valid password is found it will still change based on the validity of the next password. So the last one in the array declares the status of grantedPrompt and deniedPrompt. Try adding a break after the input is equal to one of the passwords.
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
break; // break out or loop once found
}
else
{
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}
}
You are looping through all the passwords,even though there is a match.So change the code to return the method when ever there is a match in the password.
public void actionPerformed(ActionEvent ae)
{
String input = passwordField.getText();
for(String p : password)
{
if(input.equalsIgnoreCase(p))
{
grantedPrompt.setVisible(true);
deniedPrompt.setVisible(false);
return;
}
}
grantedPrompt.setVisible(false);
deniedPrompt.setVisible(true);
}

How can I use general string in Jspinner?

I have problem with JSpinner over to show Month in JSpinner and i have follow code bellow.I use swing control with jframe form to use spinner control. When I run project it always set default value 0. How to solve this error?
static protected String[] getMonthStrings(){
String[] months=new DateFormatSymbols().getMonths();
int lastIndex=months.length-1;
if(months[lastIndex]==null || months[lastIndex].length()<=0){
String[] mS=new String[lastIndex];
System.arraycopy(months,0,mS, lastIndex,0);
return mS;
}
else{
return months;
}
}
public spinner(boolean CycleMonths) {
initComponents();
JTextField tf=null;
String[] monthStrings = getMonthStrings();
SpinnerListModel monthModel=null;
if(CycleMonths){
monthModel=new CycleSpinnerList(monthStrings);
}
else {
monthModel=new SpinnerListModel(monthStrings);
}
spMonth=new JSpinner(monthModel);
}
In your constructor code, you are calling initComponents, then creating your SpinnerListModel, creating a new JSpinner, but never adding it anywhere... So it looks like the problem is that you're just not adding the JSpinner anywhere
public spinner(boolean CycleMonths) {
initComponents();
JTextField tf=null;
String[] monthStrings = getMonthStrings();
SpinnerListModel monthModel=null;
if(CycleMonths){
monthModel=new CycleSpinnerList(monthStrings);
}
else {
monthModel=new SpinnerListModel(monthStrings);
}
spMonth=new JSpinner(monthModel);
}

Is there a way to implement classes from a file into a new file?

I have a program that is an extremely basic login:
import javax.swing.JOptionPane.*;
import java.lang.Math.*;
import java.lang.System.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JFrame;
public class UserLog extends JFrame
{
public static void main(String[]Args) throws InterruptedException
{
boolean isValid=false;
while(!isValid)
{
// Components related to "login" field
JLabel label_loginname = new JLabel("Enter your login name:");
JTextField loginname = new JTextField(15);
// loginname.setText("EnterLoginNameHere");
// Pre-set some text
// Components related to "password" field
JLabel label_password = new JLabel("Enter your password:");
JPasswordField password = new JPasswordField();
// password.setEchoChar('#');
// Sets # as masking character
// password.setEchoChar('\000');
// Turns off masking
JCheckBox rememberCB = new JCheckBox("Remember me");
Object[] array = {label_loginname,
loginname,
label_password,
password,
rememberCB};
Object[] options = {"Login", "Cancel"};
int res = JOptionPane.showOptionDialog(null,
array,
"Login",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
// User hit Login
if (res == 0)
{
System.out.println( "Login" );
}
// User hit CANCEL
if (res == 1)
{
System.out.println( "Canceled" );
}
// User closed the window without hitting any button
if (res == JOptionPane.CLOSED_OPTION)
{
System.out.println( "CLOSED_OPTION" );
}
// Output data in "login" field, if any
String newloginname = loginname.getText();
String newpassword = new String(password.getPassword());
if (newloginname.equalsIgnoreCase("Cody_Coulter") && newpassword.equals("cheche1"))
{
System.out.println("Login Successful!");
boolean selectedCB = rememberCB.isSelected();
System.out.println( "selectedCB: " + selectedCB );
Thread.sleep(3000);
Object[] array1= {"It's about time to choose"};
Object[] options1= {"Leave", "Keep Going"};
int res1 = JOptionPane.showOptionDialog(null,
array1,
"There",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options1, //the titles of buttons
options1[0]); //default button title
if(res1==1)
{
Object[] options2 = {"Answers for Algebra",
"Answers for APUSH",
"Answers for Computer Science"};
Object[] array2={"Pick Your Poison:"};
int res2= JOptionPane.showOptionDialog(null,
array2,
"This",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options2, //the titles of buttons
options2[0]); //default button title
if (res2 == 0)
{
JOptionPane.showMessageDialog(null, "Nigguh you a cheatuh" );
}
else
if (res2 == 1)
{
JOptionPane.showMessageDialog(null, "Nigguh, who's dumb enough to need to cheat in APUSH" );
}
else
if (res2 == 2)
{
JOptionPane.showMessageDialog(null, "Nigguh, you dumb" );
}
String name1 = JOptionPane.showInputDialog(null,
"What is your name?");
int length = 0;
length = newpassword.length();
String Pass = "*";
newpassword =newpassword.replaceAll(".","*");
System.out.println("Username: "+newloginname+"\nPassword: "+
newpassword+"\nName: "+name1);
}
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username or Password!");
isValid=false;
}
}
// Output data in "password" field, if any
// Output state of "remember me" check box
}
}
What I want to do is create another program, such as a fileshare, file access, or even a basic game but be able to have this login implemented in order to, of course, login. Is there a way to implement this code without having to copy and paste into another code as a separate class within that file?
Example:
public class NewGame{
public static void main(String[] args)
{
new UserLog();
}
of course this may not be syntactually correct, but that's the gist of it.
Thank you, and if I need to rephrase it or edit the question/format, let me know! :)
EDIT
After making the current main method a regular public class, and call from the newly public class, by the new main
public class gameLogin
{
public static void main(String[]args)
{
userLogin();
}
public class userLogin()
{
// current code, evidently seen in the current main
}
// rest of code
So in order to reference to the original file, userLog, I would have to (in the new file: gameLogin) use
userLog();
or would it be better to use
userLog.userLogin("Munkeeface", "password");
The simplest method would be to simply move all code from your main into a static utility-class function, and then call that function from your other classes mains. For example:
public class LoginToWebsiteUtil {
public static final void login(String username, String password, ...) {
//CODE GOES HERE
}
}
And use it with:
public class LoginToMyWebsite {
public static final void main(String[] ignored) {
LoginToWebsiteUtil.login("myname", "password", ...)
}
}
The only tricky thing will be answering the question: "what variables save state?" Those variables must be declared as static class fields in the utility class. This is because, as soon as the function ends, all state, such as the login-connection, will be terminated. In order to keep it around ("hold its state"), these state variables need to have a larger scope than just the lifetime of the function.
For example, instead of
public class LoginToWebsiteUtil {
public static final void login(String username, String password, ...) {
Connection conn = getConnectionFromLogin(username, password);
//and so on...
It will have to be
public class LoginToWebsiteUtil {
private static Connection conn = null;
public static final void login(String username, String password, ...) {
conn = getConnectionFromLogin(username, password);
//and so on...
Alternatively, you could put all the code from your original main function into the constructor of a new class, such as
public class UserLogin {
private static Connection conn = null;
public UserLog(String username, String password, ...) {
conn = getConnectionFromLogin(username, password);
//CODE HERE
}
}
But, as you can see, you still have the "what holds state?" issue.
(This is a good problem. It sounds like this login code is potentially useful in the future for you.)
Use a public method in the login class that returns whether the user has logged in or not. In the class that calls it use userLog log=new userLog(), then repeatedly call the method. If it returns true, then the user has successfully logged in.
From your code the first step (although not the best one) could be:
public class NewGame{
public static void main(String[] args) {
UserLog.main();
}
Better if you change the signature of your UserLog.main() method to have a non-static method of UserLog, e.g.
public class UserLog extends JFrame {
public void newMethod(String[] args) throws InterruptedException {
// your code in old main method
}
}
and use this method from another class as follows:
public class NewGame {
public static void main(String[] args) {
UserLog userLog = new UserLog;
userLog.newMethod(args);
}
}
If you don't pass any arguments to newMethod you can remove the params String[] args in the method definition and in the call userLog.newMethod()

Send a variable from a class to another one

I have a Jframe class that has a login and password fields. When loggin on, i have to display informations of the person that logged in, so i have to retrieve his login from the first Jframe to make a treatment in the other one.
Here is that i made, but the login returns NULL in the second jframe:
First Jframe (login and password fields):
private void button_connectActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String x= loginField.getText();
String y= passwordField.getText();
AuthentificationDAO authDAO= new AuthentificationDAO();
boolean ok_login= authDAO.verify_login(x);
int pass= Integer.parseInt(y);
System.out.println("password retrieved"+pass);
boolean ok_pass=authDAO.verify_password(pass);
System.out.println("ok pass"+ok_pass);
if (ok_login & ok_pass)
{
System.out.println("Login found!");
Enseignant e= new Enseignant();
edu.app.persistence.Enseignant ens= new edu.app.persistence.Enseignant(x);
//ens.setLogin(x);
System.out.println("login SET:"+ens.getLogin());
e.setVisible(true);
this.setVisible(false);
}
else {
System.out.println("Login NOT found!");
JOptionPane.showMessageDialog(null, "Accourt NOT found. Please check your login or password.", "Check Login/Pass", 1);
}
Second Jframe that will display informations of that login:
private void mauvaisFieldFocusGained(java.awt.event.FocusEvent evt) {
edu.app.persistence.Enseignant ens= new edu.app.persistence.Enseignant();
String login=ens.getLogin();
System.out.println("LOGIN EST:"+login);
StatsDAO stats= new StatsDAO();
int id=stats.get_id_from_login(login);
System.out.println("ID="+id);
}
Any idea please of how solving that problem?
Thank you very much.
Unless ens.login is static, this code won't work.
You can use the MVC pattern or you can just make your second frame class extends JFrame, in order to add a login field to it..
Sonething like :
class1 {
class2 frame2 = new class2();
void login(){
String x = loginField.getText();
edu.app.persist.teach ens= new edu.app.persist.teach(x);
class2.setLogin(x);
}
}
class2 extends JFrame{
String login;
String getLogin(){..}
void setLogin(String s){..}
.
.
}
I've used a sort of pseudocode but it should be clear enough

JTextField variable returns null outside of actionlistener?

I'm making a program that adds and formats files. I actually have many classes, but for the purpose of this question let's say I have two, guidialog and guimain.
In guidialog I have a JTextField and an actionlistener for it. Here is the actionlistner:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain();
blockAddWrite.addNewBlockFile();
}
});
public String blockName;
Now in guimain I have a formatter which writes a file based on the name given in the text field:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
try {
newBlock = new Formatter("Block" + blockName.blockName + ".java");
System.out.println("Created File: Block" + blockName.blockName);
} catch (Exception e) {
System.out.println("ERROR: Could Not Output Block File");
}
}
I do edit and close the file, but it wasn't necessary. But when I try this, all of the stuff in guimain that refers to blockName outputs as "null". I can't figure it out.
That's because in guimain, you're not using the blockName field of the dialog where the user entered something: you're using the blockName field of another, newly constructed dialog:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
^--- the dialog is not the one where the user entered something. It's a new one.
You should pass the blockName from the dialog to the guimain:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain(blockName); // we construct a guimain instance with the entered text
blockAddWrite.addNewBlockFile();
}
});
Side notes:
you should not use public fields. Use getter methods.
classes should be start with an upper-case and be spelt in CamelCase: GuiMain.

Categories

Resources