How to pass variable values between Jframes in NetBeans?

UPDATED: 01 November 2010
java swing JFrame Pass Values

This article stands in front of my all other articles. I got so many request to update its content for better user experience so here I am.

Swing
Swing is built on base of Abstract Window Toolkit (AWT). In other words swing is extended version of AWT for better and richer user interface. Its used to create desktop applications like chat, accounting and so on.

I'll also demonstrate how you can pass values to same JFrame without opening new JFrame.
Read more How to get list of opened JFrame in Java Swing?
Read more Sample Client - Server Chat Application in Java

Creating ParentJFrame with following components.
  • Text Field to type message
  • Button to send message

ParentJFrame Source Code
Look for the btnSendActionPerformed(java.awt.event.ActionEvent evt) method.
/* This example is coded in NetBeans so you'll find some IDE generated code unexplained. */
package com.javaquery.swing;

import java.awt.Frame;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ParentJFrame extends javax.swing.JFrame {

    public ParentJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                      
    private void initComponents() {
        lblInfo = new javax.swing.JLabel();
        textField = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Parent JFrame");

        lblInfo.setText("Message");

        btnSend.setText("Send Message");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSend)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblInfo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(textField, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblInfo)
                    .addComponent(textField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnSend)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }                        

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {                                        
        /* Get text from TextField */
        String message = textField.getText();
        String setNewMessage = "";
        boolean isFrameOpen = false;

        if (message != null && message.length() > 0) {
            /**
             * Get list of opened JFrames 
             * Read more about "How to get list of opened JFrame in Java Swing?"
             * http://www.javaquery.com/2014/06/how-to-get-list-of-opened-jframe-in.html
             */
            for (Frame frame : Frame.getFrames()) {
                /* Match title of JFrame */
                if (frame.getTitle().equals("Child JFrame")) {
                    /* Cast to ChildJFrame */
                    ChildJFrame childJFrame = (ChildJFrame) frame;
                    /**
                     * Access TextArea of ChildJFrame using getter method. 
                     * You can so same for other component like JLabel, Buttons,
                     * Combobox, List by creating getter and setter method.
                     */
                    String getPreviousMessages = childJFrame.getTextArea().getText();
                    if (getPreviousMessages.length() > 0) {
                        /* Append new message to String */
                        setNewMessage = getPreviousMessages + "\n[" + new Date().toString() + "]: " + message;
                    } else {
                        /* Create new message String */
                        setNewMessage = "[" + new Date().toString() + "]: " + message;
                    }

                    /* Set value of TextArea */
                    childJFrame.getTextArea().setText(setNewMessage);
                    isFrameOpen = true;
                }
            }

            /* If ChildJFrame is not opened yet */
            if (!isFrameOpen) {
                /* Create new message String */
                setNewMessage = "[" + new Date().toString() + "]: " + message;
                /* Create an object of ChildJFrame */
                ChildJFrame childJFrame = new ChildJFrame();
                /* Set message in TextArea */
                childJFrame.getTextArea().setText(setNewMessage);
                /* Make ChildJFrame visible */
                childJFrame.setVisible(true);
            }
        } else {
            /* Alert box when user try to send blank message */
            JOptionPane.showMessageDialog(null, "Type something to send");
        }
    }                                       

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                /**
                 * Read more about "How to apply/set up swing look and feel?"
                 * http://www.javaquery.com/2013/06/how-to-applyset-up-swing-look-and-feel.html
                 */
                try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                }
                new ParentJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnSend;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JTextField textField;
    // End of variables declaration                   
}

Creating ChildJFrame with following components.
  • Text Area (Create Getter and Setter method)
ChildJFrame is aimed to receive messages so there ain't much coding.


ChildJFrame  Source Code:
/* This example is coded in NetBeans so you'll find some IDE generated code unexplained. */
package com.javaquery.swing;

public class ChildJFrame extends javax.swing.JFrame {
    public ChildJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        scrollPane = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        lblInfo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Child JFrame");

        textArea.setColumns(20);
        textArea.setRows(5);
        scrollPane.setViewportView(textArea);

        lblInfo.setText("Message Received");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblInfo)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lblInfo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChildJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JLabel lblInfo;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTextArea textArea;
    // End of variables declaration                   

    /**
     * Getter Method
     * @return the textArea
     */
    public javax.swing.JTextArea getTextArea() {
        return textArea;
    }

    /**
     * Setter Method
     * @param textArea the textArea to set
     */
    public void setTextArea(javax.swing.JTextArea textArea) {
        this.textArea = textArea;
    }
}

I created getter and setter method to access TextArea of ChildJFrame. To access Label, Button, Combobox, etc... Create your getter and setter method.


13 comments :

  1. @Wong Song Nam: Consider you have two class say from.java, to.Java
    Now in from.java you are using button click event. In that event you need to pass values in main method of to.java (public string main(String args[]) check second image in this post or click here

    ReplyDelete
  2. I need to do this with an integer value. is this possible?

    ReplyDelete
  3. Yes you can create main method with int as a parameter and argument like public static void main(int x) and call this method from other jFrame...

    ReplyDelete
  4. It works on my project, my only problem is how to center the Frame since frame.setLocationRelativeTo(null) is not supported with this method.

    ReplyDelete
  5. http://www.java2s.com/Code/Java/Swing-JFC/Howtocenteraframeordialog.htm

    ReplyDelete
  6. Thanks Vick... btw, im the anonymous one. ^_^

    ReplyDelete
  7. Thanks Vic :) very useful tutorial.

    ReplyDelete
  8. hey is it possible to pass values after you dispose a frame??
    if not then how to that?

    ReplyDelete
  9. What exact you wanna do. You can do like before you dispose the frame pass it to another frame. Tell me the idea behind passing the value after you dispose the frame like which operation you want to do..

    ReplyDelete
  10. My Life Saver............... Thank you man for your informative details.

    ReplyDelete
  11. Thanks for the compliment and plz join G+ Page...

    ReplyDelete