Send a variable from a class to another one - java

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

Related

JFrame not "disposing" on actionperformed method

Background: I am creating a login browser page before my main UI(myGUI) page is displayed. I am using a HashMap to store the correct username and password combinations. The key is put in a getter method where I then access it from the LoginBrowser class constructor, where I build the actual UI.
Problem: Currently, the key values are stored correctly and login is successful. It properly loads up the main UI after the correct credentials are entered. I tried to instantiate the class with the key inside and then call the dispose method. However, the login browser UI does not go away afterwards. What is wrong with my instantiation and how would I solve it?
My current code:
Main method:
public static void main(String[] args) {
IdAndPasswords s = new IdAndPasswords();
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
LoginBrowser lb = new LoginBrowser(s.getInfo());
lb.setVisible(true);
//myGUI.requestFocusInWindow(); // makes sure textfield or other components don't auto focus on start-up
lb.setTitle("Chat App");
lb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
Login Browser Class Contructor:
HashMap<String,String> loginInfo = new HashMap<String,String>();
/**
* Creates new form LoginBrowser
* #param loginOG
*/
public LoginBrowser(HashMap<String,String> loginOG) {
initComponents();
this.loginInfo = loginOG;
}
Login Browser Action Performed method:
/*
If login button to perform actions
when pressed
*/
private void loginBtnActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()==loginBtn) {
String userIDNew = usernameText.getText(); // get text of JTextfield
String passwordNew = String.valueOf(passwordText.getPassword()); // get text of JPasswordfield and convert
if(loginInfo.containsKey(userIDNew)) { // key
// if entered characters in strings match up,
// display message and get rid of login browser
if(loginInfo.get(userIDNew).equals(passwordNew)) {
JOptionPane.showMessageDialog(rootPane, "Login successful");
IdAndPasswords s = new IdAndPasswords();
LoginBrowser lb = new LoginBrowser(loginInfo);
lb.dispose(); // dispose login browser
// Once old form is disposed, open main gui form
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
myGUI myGUI = new myGUI(userIDNew);
myGUI.setVisible(true);
//myGUI.requestFocusInWindow(); // makes sure textfield or other components don't auto focus on start-up
myGUI.setTitle("Chat App");
myGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
// tell user if info entered is incorrect
} else {
JOptionPane.showMessageDialog(rootPane, "Incorrect Password");
}
} else {
JOptionPane.showMessageDialog(rootPane, "Incorrect Username");
}
}
}
Instead of instantiating class with key:
LoginBrowser lb = new LoginBrowser(loginInfo);
lb.dispose(); // dispose login browser
Simply use this. to control JFrame from within design feature of netbeans:
this.dispose();

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

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

Forcing a JPanel to repaint after calling the show method of CardLayout

I'm writing a holiday recommendation system for a piece of coursework. The GUI of which uses CardLayout. In the main class a user object is created with default name and access levels defined in it's constructor. this object is passed from main to the UserCard panel which passes it to Login and logged in.
if the user successfully logs in then the cardpanel transitions from Login to logged in and is supposed to display the username of the logged in user by calling the user.getUsername(); method.
my problem is thus. because of the way card layout works the panel with the username display has already been created in the constructor of UserCards with the default values from then the user object was first created. I need to find a way to force this panel to repaint after the show method is called on the cardlayout object. The following is the code of the 3 classes in question. (I've limited the code paste to the relevant methods).
//the usercards panel
public UserCards(User u)
{
CardLayout cl = new CardLayout();
this.setLayout(cl);
UserOptionsPanel options_card = new UserOptionsPanel(cl, this);
RegisterPanel register_card = new RegisterPanel(cl, this);
LoggedInPanel loggedin_card = new LoggedInPanel(cl, this, u);
LoginPanel login_card = new LoginPanel(cl, this, u, loggedin_card);
this.add(options_card, options);
this.add(login_card, login);
this.add(register_card, register);
this.add(loggedin_card, loggedin);
}
//the Loggin action listener user is passed in as a reference to the user object created in //main. the createUser(); method is a badly named method that simply calls setter methods on //the user object's fields
#Override
public void actionPerformed(ActionEvent e)
{
String[] vals = packData();
try
{
DBConnection d = new DBConnection();
Connection conn = d.getConnection();
Validation v = new Validation(vals, user);
v.getActual(conn);
if(v.validate())
{
user = v.createUser();
System.out.println(user.getUserName());
l.revalidate();
cl.show(pane, "loggedin");
}
else
{
lbl_statusmsg.setText("Password Incorrect");
lbl_statusmsg.repaint();
}
}
catch(ClassNotFoundException | SQLException ex)
{
ex.printStackTrace();
}
}
//the loggedin constructor
public class LoggedInPanel extends JPanel
{
private User user;
private JLabel lbl_details;
public LoggedInPanel(CardLayout cl, Container pane, User u)
{
super();
user = u;
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
lbl_details = new JLabel();
lbl_details.setText("Welcome "+user.getUserName());
this.add(lbl_details);
}
}
Apologies if I've not been overly clear I'm not given to asking for help :)
Do you mean something like ?
CardLayout cl = new CardLayout() {
#Override
public void show(java.awt.Container parent, String name) {
super.show(parent, name);
// your code here
}
};

getText() vs getPassword()

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

Categories

Resources