Calling a method on an object of another class without - java

I've got three classes: User, UserManagement (containing an arraylist of users) and LoginController.
public class UserManagement {
//Create an arraylist that stores users
ArrayList<User> users;
public UserManagement() {
users = new ArrayList<User>();
}
public void addUser(String userName, String fullName, String password) {
users.add(new User(userName, fullName, password));
}
public void listAllUsers() {
for (User user : users) {
System.out.println(user.printUserInfo());
}
}
/**
*
* #param userName username to be searched for
* #param password password to be searched for
* # return boolean for check of username/password
*/
public boolean checkUser(String userName, String password) {
int index = 0;
boolean searching = true;
boolean match = false;
while (searching && index < users.size()) {
String u = users.get(index).getUsername();
String p = users.get(index).getPassword();
if (u.equals(userName) && p.equals(password)) {
//its a match
match = true;
}
else {
// continue searching
index++;
}
}
return match;
}
}
public class LoginController implements Initializable, ControlledScreen {
#FXML
Button loginButton;
#FXML
private TextField login;
#FXML
private PasswordField password;
ScreensController myController;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void setScreenParent(ScreensController screenParent) {
myController = screenParent;
}
#FXML
private void handleButtonAction(ActionEvent event) {
UserManagement.users.checkUser(login.getText(), password.getText());
//something like this? ^
}
}
What I would like to do is to call the method checkUser with variables I have stored in the LoginController class. Obviously I don't want to create a bunch of arraylists whenever I want to check login details. Is there a way of doing this to the arraylist in UserManagement without creating a new arraylist every time?
The last method in LoginController may give better insight to what I like to achieve.

UserManagement.users.checkUser(login.getText(), password.getText());
won't work because users is defined as a member variable in UserManagement class. Whereas UserManagement.users is trying to get the class variable.
Here's a link that tells you the difference:
http://www.programmerinterview.com/index.php/c-cplusplus/whats-the-difference-between-a-class-variable-and-an-instance-variable/
Quick fix:
1) instantiating a UserManagement instance in your LoginController class.
public class LoginController implements Initializable, ControlledScreen {
#FXML
Button loginButton;
#FXML
private TextField login;
#FXML
private PasswordField password;
ScreensController myController;
UserManagement usrMgmt = new UserManagement();
....
then you can do :
#FXML
private void handleButtonAction(ActionEvent event) {
usrMgmt.checkUser(login.getText(), password.getText());
//something like this? ^
}

A few tips :
1) Don't initialize the ArrayList in the constructor of UserManagement Class. Think of it like "Everytime someone instantiates that Class, a new arraylist will be created...Do I want that?"
It is not appropriate and also unnecessary usage of space.The Solution here would be to have it like a property and have getters and setters for it. This will resolve your class design conondrum of creating an ArrayList everytime the constructor is called.
private ArratList<User>; {get;set;}
2) In the checkUser() function, you are checking existence of all users and their passwords. Never do that.
Instead, select the user and check if he exists, only then check if his password is correct or not. Return the result as appropriate (Separating errors like User does not exist or incorrect password etc).

Related

Accessing variables from another classes with setter and getter JAVA

This is a very simple example of my project which is a lot more bigger in scale.
Tasks:
The password will be set at the setpassword method.
The getpassword method will return the password.
The password is called at sendmail class in order to be send via email to the user to log in with the new credentials.
But When I run the whole code everything works except that the sendmail class won't access the password from the getpassword method in users class.
I put a simple version of my code:
users class >>>>>
public class users {
private String password;
public users (){}
// GETTING PASSWORD
public String getpassword(){
return password;
}
// SETTING PASSWORD
public void setapassword(String password){
this.password=password;
}
}
Signup class>>>>>>
public class signup {
public void signsup(){
users user1 =new users();
user1.setapassword("player");
sendmail mail1 =new sendmail();
mail1.Sendsmail();
}
}
sendmail class>>>>
public class sendmail {
public void Sendsmail(){
users user1 =new users(); // object
user1.getpassword(); //getting password
System.out.println(user1.getpassword()); // If print here I get null
}
}
Main signup Class>>>>
public class SignupMain {
public static void main(String[] args) {
signup signup1= new signup();
signup1.signsup();
}
}
The user1 object from your signup class and your sendmail class are different. Surely their variable is named the same way but they refer to different Objects. To access the password from the user you have to pass the user to the sendmail class e.g.:
Signup.java
public class signup
{
public void settingPassowrd()
{
users user1 = new users();
user1.setapassword( "player" );
sendmail mail1 = new sendmail();
mail1.Sendsmail(user1);
}
}
with:
public class sendmail
{
public void Sendsmail(user usr)
{
usr.getpassword(); // getting password
System.out.println( usr.getpassword() ); // will be the proper value from now on.
}
}
Please follow the standard coding conventions. I changed your code with standard coding conventions. just copy paste it , it will work
Users class
public class Users {
private String password;
public users (){}
// GETTING PASSWORD
public String getpassword(){
return password;
}
// SETTING PASSWORD
public void setapassword(String password){
this.password=password;
}
}
Signup class
public class Signup {
public void settingPassowrd(){
Users user1 =new Users();
user1.setapassword("player");
SendMail mail1 =new SendMail(user1);
mail1.Sendsmail();
}
}
SendMail class
public class SendMail {
private Users user1;
SendMail(Users user1){
this.user1 = user1
}
public void sendMail(){
user1.getpassword(); //getting password
System.out.println(user1.getpassword()); // If print here I get null
}
}
Main class to test the code
public class SignupMain {
public static void main(String[] args) {
Signup signup1= new Signup();
signup1.settingPassowrd();
}
}
Problem is that in your sendmail class you create a new user users user1 =new users(); --> so you don't access the user you previously created, but you create a new one which obviously does not have a password.
Instead, pass your user to the sendmail function in the signup class:
public void settingPassowrd(){
users user1 =new users();
user1.setapassword("player");
sendmail mail1 =new sendmail();
mail1.Sendsmail(user1);
}
and in class sendsmail:
public void Sendsmail(users user) {
System.out.println(user.getpassword());
}
By the way, I suggest you read some coding guidelines for Java. for example:
Class names should always start with a capital letter
Class names are usually singular (class users --> class User)
Method names always start with a lowercase letter and use camelCase (getpassword() --> getPassword())

Java:Calling method, initialized in one class, gives Nullpointerexception in other class

I defined a Logininfo class to store the email and password of a user in. I get the email and password from a Login GUI. There are put into the Logininfo class using setMethods. I'm connecting the programming to a mysql server (mysql is not an issue here). I need the the emailadres and password so I can use it for queries in other GUI's later on.
This is the Logininfo class
public class Logininfo {
public static Emailadres emailadres = new Emailadres();
public static Password password = new Password();
public static class Emailadres
{
private String emailadres;
public Emailadres()
{
emailadres = " ";
}
public void setEmailadres(String emailadres)
{
this.emailadres = emailadres;
}
public String getEmailadres()
{
return(emailadres);
}
}
public static class Password
{
private String password ;
public Password()
{
password = " ";
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return(password);
}
}
}
In the login GUI I use the setMethod to store the emailadress and password.
public class Login extends javax.swing.JFrame {
Logininfo logininfo;
Logininfo.Emailadres emailadres = new Logininfo.Emailadres();
Logininfo.Password password = new Logininfo.Password();
private boolean validate_login(String email,String wachtwoord) {
emailadres.setEmailadres(email);
wachtwoord.setPassword(password);
Later on I try to retrieve the emailadress and password in another class.
public class Account extends javax.swing.JFrame {
Logininfo logininfo;
Logininfo.EmailAdres emailadres;
Logininfo.WachtWoord password;
emailadres.getEmailadres(email);
password.getPassword(password);
I get a Nullpointerexception here. I know that you have to make a new instance of Logininfo in the Login GUI screen. However in the Account class you can't make another new instance. Are public class not supposed to be used for this and should I use something else?
Any help would be appreciated
email_adres in your Login class is an instance field of that class, and is completely unrelated to emailadres instance field of Account class. The two pointers point to different places in memory.
If you want the instance of Account to have that data from Login instance, you have to give it to it somehow.

Simple button code using interface

I'll write the code first and ask my question below
Below is my main class
public class Application {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
runApp();
}
});
}
public static void runApp() {
Model model = new Model();
View view = new View(model);
Controller controller = new Controller(view, model);
view.setLoginListener(controller);
}
}
Below is my another class
public class LoginFormEvent {
private String name;
private String password;
public LoginFormEvent(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Below is my controller class
public class Controller implements LoginListener {
private View view;
private Model model;
public Controller(View view, Model model) {
this.view = view;
this.model = model;
}
#Override
public void loginPerformed(LoginFormEvent event) {
System.out.println("Login event received: " + event.getName() + "; " + event.getPassword());
}
}
Below is my LoginListener interface
public interface LoginListener {
public void loginPerformed(LoginFormEvent event);
}
Lastly below is my view class which I have just deleted the JFrame code for simplicity.
public class View extends JFrame implements ActionListener {
private Model model;
private JButton okButton;
private JTextField nameField;
private JPasswordField passField;
private LoginListener loginListener;
#Override
public void actionPerformed(ActionEvent e) {
String password = new String(passField.getPassword());
String name = nameField.getText();
fireLoginEvent(new LoginFormEvent(name, password));
}
public void setLoginListener(LoginListener loginListener) {
this.loginListener = loginListener;
}
public void fireLoginEvent(LoginFormEvent event) {
if(loginListener != null) {
loginListener.loginPerformed(event);
}
}
}
It is a standard button coordinating code so you guys probably won't even need to read my code to answer my question.
So I know how to write this code and this is how I write it when I want a button to do call some action. But when I try to get my logic around it to understand 'why' it works, I get very confused.
so when I call view.setLoginListener(controller) I'm obviously expecting some kind of LoginFormEvent.
Then when I click the button, in the view class, new LoginFormEvent is constructed.
But then how is the constructed LoginFormEvent within the view class be set as the parameter of expected LoginFormEvent in controller class when there's not really any connection between the two classes except that I have defined view.setLoginListener(controller) in the Application class. This just makes setLoginListener of particular instance of view to expect some kind of LoginListener, meaning it doesn't really have to be the one that I set up in the view class upon a click of a button? But obviously it does have to be because that's how the code is run. but why?
You can see the flow as below
Lets start withApplication.java. lets see the method runApp(). It does below things.
Objects of View.java and Controller.java are created.
Controller.java implements LoginListener.java
view.setLoginListener(controller); // this sets the object of
Controller.java in the object of View.java, both these objects are
same as created in step-1.
Now lets move to View.java
It has a field private LoginListener loginListener; and method public void setLoginListener(LoginListener loginListener). This method sets the field loginListener As we see above in step 2 loginListener refers to the same object of Controller.java created in step 1 above.
Now lets move to public void actionPerformed(ActionEvent e) defined in View.java.
It calls fireLoginEvent(new LoginFormEvent(name, password)); See now Object of LoginFormEvent.java is created and it is passed as a parameter to the method fireLoginEvent(LoginFormEvent event).
Now moving to public void fireLoginEvent(LoginFormEvent event)
It has code : loginListener.loginPerformed(event);. From above we know loginListener refers to the one and only object of Controller.java
method public void loginPerformed(LoginFormEvent event) on that very object of Controller.java is called and same object of (again one and only one) LoginEvent.java is passed as parameter.
For such type of scenarios, I would recommend you to note the objects created of each type and connect the flow of calls. Hope above helps you understand the code.

How to get text from JTextField, convert to a string, and use this string in a different java public class

I have a GUI that has 2 JTextFields- EmailLoginField and jPasswordField1. Ill just discuss the EmailLoginField and just duplicate what is recommended on jPasswordField1 too.
So heres some GUI code:
package p;
imports ...
public class EmailLoginGUI extends javax.swing.JFrame {
public EmailLoginGUI() {
initComponents();
}
private void initComponents() {
...
EmailLoginField = new javax.swing.JTextField();
}
...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
EmailMainGUI open = new EmailMainGUI();
open.setVisible(true);
This next code snippet is what I have tried to do to get the text from the JTextField EmailLoginField in EmailLoginGUI.java
public String getEmailLoginField(){
return EmailLoginField.getText();
}
public String getjPasswordField(){
return jPasswordField1.getText();
}
Here is the next part (not assuming the code immediately above is correct). This next code is an entirely different public class, which same package of course. Here is what I have tried it should look at the EmailLoginGUI class and get the JTextField content, eventually storing it as a String.
PLEASE NOTE: the final strings that contain the JTextField content MUST NOT be inside the SendEmail(EmailLoginGUI c1, EmailLoginGUI c2){. They should be just outside of it just inside public class SendEmail { this is so that they can be used by other code later.
package p;
imports ...
public class SendEmail {
JTextField userTF;
JPasswordField passPF;
SendEmail(EmailLoginGUI c1, EmailLoginGUI c2){
userTF.setText(c1.getEmailLoginField());
passPF.setText(c2.getjPasswordField());
}
public String user(){
return userTF.getText();
}
public String pass() {
return passPF.getText();
}
...
SendEmail(...) {
Properties props = new Properties();
...
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return new javax.mail.PasswordAuthentication(user(), pass()); //This is where the final strings need to go.
}
});
Hopefully what I am trying to do is clear:
Get the content from JTextField created in EmailLoginGUI.java. Get this into SendEmail.java. Its final type should be String and is 'just on the inside' of the public class SendEmail. I have had everything from NullPointerException to Cannot find symbol for hours! Think I've been attempting it for so long that I could benefit from some fresh eyes!
Help would be greatly appreciated.
In SendEmail class create Constructor which has an argument of user input
SendEmail(String userInput) {
//Your Code
}
In EmailLoginGUI create
String userInput = EmailLoginField.getText().toString();
SendEmail sendemail = new SendEmail(userInput);
This method works I have used it. Hope it helps.
I realised both the security risk and how a dialogue would be easier, however I don't have time to go back to change it really. I have already coded the listener too so that's not a problem. But yes that's what I want to do! Where am I going wrong?
Then you need to implement some kind of Observer Pattern.
Start by defining the expected operations that the login view might generate, for example, it's reasonable to expect that the user can either accept or cancel the view
public interface EmailLoginListener {
public void emailLoginWasAccepted(EmailLoginGUI gui);
public void emailLoginWasCanceled(EmailLoginGUI gui);
}
Update the view to provide support for the listener
public class EmailLoginGUI extends javax.swing.JFrame {
private List<EmailLoginListener> listeners;
public EmailLoginGUI() {
initComponents();
listeners = new ArrayList<>(25);
}
//...
public void addEmailLoginListener(EmailLoginListener listener) {
listeners.add(listener);
}
public void removeEmailLoginListener(EmailLoginListener listener) {
listeners.add(listener);
}
protected void fireLoginWasAccepted() {
for (EmailLoginListener listener : listeners) {
listener.emailLoginWasAccepted(this);
}
}
protected void fireLoginWasCanceled() {
for (EmailLoginListener listener : listeners) {
listener.emailLoginWasCanceled(this);
}
}
}
In your action handlers for your buttons on the EmailLoginGUI view, trigger the required event...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
fireLoginWasAccepted();
}
Remember, you should also do this for the cancel operation if you have one.
Now, when you create an instance of EmailLoginGUI, make sure you also register a EmailLoginListener with it
EmailLoginGUI loginView = new EmailLoginGUI();
loginView.addEmailLoginListener(new EmailLoginListener() {
#Override
public void emailLoginWasAccepted(EmailLoginGUI gui) {
gui.dispose();
String email = gui.getEmailLoginField();
String password = gui.getjPasswordField();
EmailMainGUI open = new EmailMainGUI();
open.setCredentials(email, password);
//...
open.setVisible(true);
}
#Override
public void emailLoginWasCanceled(EmailLoginGUI gui) {
// Exit the program?
gui.dispose();
}
});
//...
loginView.setVisible(true);
This will require you to either change the constructor of EmailMainGUI to accept the email and password or a method to pass that information to the class (as I've demonstrated above)
Finally change SendEmail to accept String values instead of your gui components
public class SendEmail {
String email;
String password;
SendEmail(String email, String password) {
this.email = email;
this.password = password;
}
public String user() {
return email;
}
public String pass() {
return password;
}
}

Sending Text Field values from a swing class to another class

So, i'm building a login form in java with swing.
and i did this test when login button is clicked
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String username = jTextField1.getText();
String password = jTextField2.getText();
if (username.equals("Admin")&&password.equals("Admin")) {
//Launch admin panel
AdminGui admin = new AdminGui();
admin.setVisible(true);
}
else {
//Some code
}
}
As you see if the username = Admin and the passowrd is also Admin AdminGui will launch, but i want this test to be performed at another class.
How could i send the textfield values from this class to another ?
First option is to send it using the constructor like:
AnotherClass ac = new AnotherClass (yourInput);
or:
AnotherClass ac = new AnotherClass (yourInput);
ac.setYourInput(yourInput);
You could make a Utility-class which you should do, because of the MVC-pattern:
public static class YourUtilityClass{
public static boolean checkLogin(String username, String password){
if(username.equals("Admin") && password.equals("Admin")){
return true;
}else{
return false;
}
}
And in your GUI in your actionPerformer-method you have to do something like that:
boolean loginCorrect = YourUtilityClass.checkLogin(username,password);
if(loginCorrect){
//login was okay and you can load the AdminGui
}else{
//notCorrect
}
Create another class, called maybe UserService, e.g.
public class UserService {
public boolean isValidLogin(String username, String password) {
return username.equals("Admin") && password.equals("Admin");
}
}
Create an instance UserService in your class which has jButton1ActionPerformed method. e.g
Note if you have another class that creates the view you should really pass this on instead with a getter/setter method.
private UserService userService = new UserService();
Then call in your jButton1ActionPerformed() method
if (userService.isValidLogin(username, password)) {

Categories