So you started learning java and someone told you to use NetBeans IDE as it will make your work easier by providing a easy-to-use drag & drop GUI builder. Yes, it does. It really makes programming easy for a beginner by removing all the coding required for the designing part. But problems crops up when you go advanced. And when you search the web for help, you would really find it difficult to understand other’s answers.
One such problem for which it would be difficult to get answer for, is passing values from one JFrame form to another.
So, here’s is a simple guide to help you move forward.
To know how to pass a value/variable from one form to another, you need to know ‘What is a Constructor?’.
Constructor
♦ A Constructor is like method which has the same name as it’s class.
♦ It is used to initialize the objects of that class type with a legal initial value.
♦ When you create a object of a class, the compiler automatically calls it’s constructor.
♦ Constructor has no return value, not even void.
So, we would have to overload the class’s constructor in which we want to get the value. I have designed two simple JFrame forms, the first is a login screen in which a user would enter his username and password and second is a welcome screen in which we will get his username from the previous screen and display it in a label.
Here’s the design view of the both the forms.
Double click the Log in button to open it’s actionPerformed event and paste the following code:-
String user=jTextField1.getText();
String pwd= new String (jPasswordField1.getPassword());
if (user.equals(“admin“) && pwd.equals(“pass“))
new Welcome(user).setVisible(true);else {JOptionPane.showMessageDialog(this, “Incorrect Username or Password!”);}
As soon as you paste the code, you will see a error and NetBeans will ask you to create a constructor Welcome(java.lang.String), ignore this warning for now.
As you can see, we are passing the variable user(which stores are username i.e admin) in the constructor for the Welcome form. Now, open the source tab in your Welcome form and find it’s default constructor and paste/type the following code below it:-
public Welcome(String User) {username = User;
initComponents();}
Now, declare String variable username just below your class declaration. Your code should now look like this-
public class Welcome extends javax.swing.JFrame {String username;
/*** Creates new form Welcome*///Default constructorpublic Welcome() {initComponents();}//Our new constructorpublic Welcome(String User) {username = User;initComponents();}
Now, right click your welcome form and go to>Events>Window>windowOpened and use the username variable set it wherever you want!
Example:-
userTF.setText(username);
Now, go back to login form and press Shift + F6 to run your file. Enter your username and password and click login to see your name on the next screen.
You might be thinking now that why have two constructor, this is because netbeans let’s us to run a single JFrame Form so if delete the old the constructor then the Runnable which is placed at the end of your code will cause you errors.
Not just a simple string, you can pass any variable from one form to another and ofcourse you can pass a value further that you received from the previous class. So, let’s move onto another example.
Now from the welcome screen we will take an int value i.e age and a list of hobbies and pass on these values including username to a new screen. As you know we can initialize variables in the constructor, so I have declared an ArrayList under class declaration and initialized it in the constructor so that we can use it in any event we want. Here’s what code looks like now-
Welcome.java (only relevant part)
public class Welcome extends javax.swing.JFrame {String username;
ArrayList hobbies;/**
* Creates new form Welcome
*/
//Default constructor
public Welcome() {
initComponents();
}//Our new constructor
public Welcome(String User) {
username = User;
hobbies = new ArrayList();
initComponents();
}
In details form we will initialize the 3 variables that has been passed through the constructor. We will show username and age in labels and hobbies jList component.
Details.java
package demoforblog;import java.util.ArrayList;import javax.swing.DefaultListModel;/**** @author Rohan*/public class Details extends javax.swing.JFrame {int age;
ArrayList hobbies;
String user;
/**
* Creates new form Details
*/
public Details() {
initComponents();
}
public Details(int AGE, ArrayList HOBBIES, String USER) {
age = AGE;
hobbies = HOBBIES;
user = USER;
initComponents();
}private void formWindowOpened(java.awt.event.WindowEvent evt) {System.out.println(“”+age);System.out.println(“”+hobbies.get(0));jLabel6.setText(user);jLabel7.setText(“”+age);DefaultListModel list = new DefaultListModel();for (int i =0; i < hobbies.size(); i++ ) {list.addElement(hobbies.get(i));}jList1.setModel(list);}
Note:- >You have guessed it right the back button does nothing.
>System.out statements are only for testing, you can ignore them.
Now run your login form again to see all the screens in action.
I have used different colors, so that you don’t get confused with the variables, but if you still have any problem regarding it then the image below could help you.
Great tutorial very helpful!!
I would like your next one to talks about data management(add, retrieve, update, filtering , delete) on Jtable with data coming from database
keep it up!
thanks a lot!!
thanx for this tutorial…
this will help me a lot…
can u suggest some more ways to connect mySQL with netbeans….. other than mentioned in class 12 informatics practices book of cbse……..
Thanks a lot.. this is very helpful.
I have a question.. How about passing a value from a form to an Open form?
thank you so much..
wowww.mast hai bhai
I USED USED THE CODE AND IT WORKED LIKE MAGIC, KEEP UP THE GOOD WORK.
hey mate thanks for the code but one question though
i am able to login and get the username but i have multiple frames and i navigate from one frame to home again then the username appears null.
any fix!!
You have to pass the variable again, it will not be stored. i.e you have to pass it through your form to the home form again like this : new Welcome(user).setVisible(true);
i am not having the variable i need to pass in the for i am.
its in some other form
so how do i pass it from that form to haome even when i am navigating a third form!!
You can declare your variable as 'public static', then you can access it from any other form like this:
String user = Home.myvariable;
thanks
Hi very thanks for your notes… send me your email id my email id is selvamvinsoft@gmail.com bcz i am a fresher i have some doubt plz help me
Very well explained tutorial. You are a great guy helping beginners like us to become experts. All other websites just do some crap which we dont understand but you explain it superbly. Keep up the good work man!! I will suggest this site to everyone. This is the least I can do.
Thanks for the appreciating words. I know how bad it feels when the whole day is wasted just because a single line of code was not known or understood. I try to share all that things which made me confused as a beginner. Keep reading and sharing, more tutorials on it's way.
Hey Rohan, I am using this code for a log-in system which is connected to Access Database and I need 3 different people to log-in who will then be directed to their JFrame, can you please see my code and tell me how can i edit it, the other JFrame names are
1.Event Managers will be directed towards BookingDetails.java
2.Receptionist will be redirected towards Receptionist.java
3.Administrator will be directed towards Halls.java
import java.sql.*;
import javax.swing.*;
public class LoginMenu extends javax.swing.JFrame {
Connection conn=null;
ResultSet rs =null;
PreparedStatement pst=null;
/**
* Creates new form LoginMenu
*/
public LoginMenu() {
initComponents();
conn= JavaConnect.ConnectDb();
}
private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql ="select * from LoginID where username=? and passwordname=? ";
try{
pst=conn.prepareStatement(sql);
pst.setString(1,txt_username.getText());
pst.setString(2,txt_password.getText());
rs=pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password is correct" );
Receptionist s =new Receptionist();
s.setVisible(true);
}
else
JOptionPane.showMessageDialog(null, "Invalid username and Password" );
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e );
}
}
private void cmd_exitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
conn= JavaConnect.ConnectDb();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginMenu().setVisible(true);
}
});
}
// Variables declaration – do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JButton cmd_exit;
private javax.swing.JButton cmd_login;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPasswordField txt_password;
private javax.swing.JTextField txt_username;
// End of variables declaration
}
You have two user(s): "user" variable and User like "String User." I thinking this is the part I'm confusing. What is the "User" in "String User" exactly?
it's nothing, it's just a parameter. You can replace it with any other character/word.
Okay. now I'm really confused. How can it be nothing? The word "User" – as in "public Welcome(String User)" – seems to be the only real link between the first frame and the second one. If I replace it with any other character/word then where's the connection? By the way, I tried replacing it and error messages galore. Please, what am I doing wrong?
if you change this:
public Welcome(String your_changed_word)
then you've to change this also
username = your_changed_word;
Have you just copied the codes or read the article too?
Go through the article again, also must see the last image.
If still problem, learn about methods here: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Specially, read the parameters part.
Thanks man, this helped a lot. I would be able to make my IP project better!
I had been trying to pass the value from one form to the next for the last two days. All the other solutions on the internet were very vague or way over a beginners level. This has been the most helpful, understandable site. Kudos to Rohan!! Two thumbs up!! Thank you very much!!
its was very helpful.. thanks a million..!!! 🙂
Thanks dear
This is very fruitful work for me because this code me some idea that i m going to use some application. My email id is gupta.girijesh@gmail.com. Sir May i ask any question whenever i face trouble in coding
what if i needed to grant access to a list of users?
this is only for admin with password pass.
please help
thank you so much sir!
but i didn't understand the purpose behind
userTF.setText(username);
also i want the first page to hide once i have moved onto the next page.
i tried doing this
new p1().setVisible(false); in the constructor of second page but nothing happened
p1 is the first page frame.
1) That's just to demonstrate. The name entered in the previous screen is displayed as a welcome message.
2) use dispose(); below the line new Welcome(user).setVisible(true);
it worked!
thanks for the timely reply 😀
Thanks a lot. Helped a great deal in my project.
Thank you so much man you solved my problem you are great thanks alot;
A.K.Shady
Thanks a lot
god bless you
you are the best
really helpfull 🙂
if i have a data in database, and i want to loop the data and produce a list of checkbox.. how should i do it?
thank you so much
what if the previous form in a state close? whether they can be accessed or not?
Your tutorial is fantastic! It explains everything so clearly. Spent ages on Google trying to figure out how to do this before I came across this. Thank you so much!
This comment has been removed by the author.
anuj32.net46.net/desktop
thank you it works well….
Explained in a very neat and simple manner..Thanks..that was a home run..:)
I Have 2 Class In JFrame
Class 1 As Main, Class 2 As PopUp..
I Want To SetText My JTextFields In Class 1 From Class 2..
AnyOne Can Help..??