Passing Value from one Form to Another in NetBeans

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 constructor
    public Welcome() {
        initComponents();
    }
   
    //Our new constructor
    public 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();
}

private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
        int age = Integer.parseInt(jTextField1.getText());
       
        if (jCheckBox1.isSelected())
            hobbies.add(“Reading”);
        if (jCheckBox2.isSelected())
            hobbies.add(“Photography”);
        if (jCheckBox3.isSelected())
            hobbies.add(“Blogging”);
        if (jCheckBox4.isSelected())
            hobbies.add(“Programming”);
       
        new Details(age, hobbies, username).setVisible(true);

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.

 

40 thoughts on “Passing Value from one Form to Another in NetBeans”

  1. 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!!

  2. 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……..

  3. Thanks a lot.. this is very helpful.

    I have a question.. How about passing a value from a form to an Open form?

  4. 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!!

  5. 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!!

  6. 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.

  7. 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.

  8. 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
    }

  9. 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?

  10. 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?

  11. 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!!

  12. what if i needed to grant access to a list of users?
    this is only for admin with password pass.
    please help

  13. 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.

  14. 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);

  15. 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!

Leave a Comment

Your email address will not be published. Required fields are marked *