Transferring Data Between JFrame Windows

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class DataTransferMasterDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            FirstWindow first = new FirstWindow();
            first.setVisible(true);

             // Programmatic transfer demonstration:
            first.t1.setText("John Deo");
            first.b1.doClick();
        });
    }
}

class FirstWindow extends JFrame {
    JTextField t1;
    JButton b1;

    public FirstWindow() {
        setTitle("First Window");
        setBounds(100, 100, 360, 200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(null);

        t1 = new JTextField();
        t1.setBounds(30, 30, 180, 25);
        getContentPane().add(t1);

        b1 = new JButton("Submit");
        b1.setBounds(220, 30, 90, 25);
        b1.addActionListener(e -> {
            String str = t1.getText();
            SecondWindow second = new SecondWindow();
            second.my_update(str);
            second.setVisible(true);
            dispose();  // Close first window
            System.out.println("Data transferred: '" + str + "' | FirstWindow disposed.");
        });
        getContentPane().add(b1);
    }
}

class SecondWindow extends JFrame {
    private JLabel l1;

    public SecondWindow() {
        setTitle("Second Window");
        setBounds(150, 150, 360, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        l1 = new JLabel("Waiting for data...");
        l1.setBounds(30, 30, 280, 25);
        getContentPane().add(l1);
    }

    public void my_update(String str) {
        l1.setText("Received: " + str);
    }
}

Output:

Data transferred: 'John Deo' | FirstWindow disposed.
[GUI Output: FirstWindow disposed, SecondWindow active with JLabel="Received: John Deo"]

1. Designing the First JFrame (First.java) 🔝

Create First.java with Absolute Layout, a JTextField (t1), and a Submit JButton (b1):

Swing First window

2. Designing the Second JFrame (Second.java) 🔝

Create Second.java with Absolute Layout and add a JLabel (l1):

Swing Second window

3. Passing Data via Setter / Method Injection (my_update) 🔝

In Second.java, define my_update(String str):

public void my_update(String str) {
    l1.setText(str);
}

In First.java, add the button action handler:

b1.addActionListener(e -> {
    String str = t1.getText();
    Second obj = new Second();
    obj.my_update(str);
    obj.setVisible(true);
    dispose(); // Close First.java cleanly
});

4. Alternative: Constructor Injection (Clean Architecture) 🔝

Pass data directly into the constructor:

import javax.swing.*;

public class ConstructorInjectionWindow extends JFrame {
    private JLabel l1;

     // Passing data directly via constructor:
    public ConstructorInjectionWindow(String userName) {
        setTitle("User Profile");
        setSize(320, 180);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(null);

        l1 = new JLabel("Welcome, " + userName + "!");
        l1.setBounds(30, 30, 250, 25);
        add(l1);
    }

    public static void main(String[] args) {
        ConstructorInjectionWindow win = new ConstructorInjectionWindow("Alice Smith");
        System.out.println("Constructor injection verified: " + win.getTitle());
    }
}

Output:

Constructor injection verified: User Profile

5. Managing Window Lifecycle: dispose() vs setVisible(false) 🔝

Compare hiding windows versus disposing OS resources:

import javax.swing.JFrame;

public class DisposeVsHideDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("Test Window");
        f.setSize(200, 100);

        f.setVisible(false);  // Window hidden, but native OS resources retained in RAM
        System.out.println("After setVisible(false): isDisplayable=" + f.isDisplayable());

        f.dispose();          // Releases window peer and OS memory resources
        System.out.println("After dispose(): isDisplayable=" + f.isDisplayable());
    }
}

Output:

After setVisible(false): isDisplayable=true
After dispose(): isDisplayable=false

6. Two-Way Communication with Listener Callbacks 🔝

Pass modified data back to the parent using a callback interface:

interface DataCallback {
    void onDataReturned(String result);
}

class ChildDialog {
    public void submitResult(DataCallback callback, String data) {
        callback.onDataReturned(data);  // Send result back to parent
    }
}

public class TwoWayDataTransferDemo {
    public static void main(String[] args) {
        ChildDialog dialog = new ChildDialog();
        dialog.submitResult(returnedData -> {
            System.out.println("Parent received callback result: " + returnedData);
        }, "Updated Record #42");
    }
}

Output:

Parent received callback result: Updated Record #42

7. Shared Session Models for Multi-Window Applications 🔝

Store user session data in a shared class:

class AppSession {
    private static String currentUser;
    public static void setUser(String user) { currentUser = user; }
    public static String getUser() { return currentUser; }
}

public class SharedModelTransferDemo {
    public static void main(String[] args) {
        AppSession.setUser("admin@plus2net.com");
        System.out.println("Shared model user in Window B: " + AppSession.getUser());
    }
}

Output:

Shared model user in Window B: admin@plus2net.com

Modal dialogs block parent interaction until dismissed:

import javax.swing.*;

public class ModalDialogTransferDemo {
    public static void main(String[] args) {
        JFrame parent = new JFrame("Parent");
         // Modal dialog blocks input to parent until closed:
        JDialog dialog = new JDialog(parent, "Select Option", true);
        dialog.setSize(250, 150);
        System.out.println("Modal dialog configured with parent: " + dialog.isModal());
    }
}

Output:

Modal dialog configured with parent: true

9. Comparison: Multi-Window Communication Strategies 🔝

Pattern Data Direction Best Used For
Setter Injection (my_update) Parent → Child WindowBuilder visual forms where GUI components initialize in constructor.
Constructor Injection Parent → Child Immutable data required before the window is rendered.
Callback Interface Child → Parent Popup pickers (color, date, or customer selection dialogs).
Shared Singleton Model Omnidirectional (Global) Logged-in user profiles, database connections, application themes.

» Next Tutorial: Displaying Tabular Data with JTable

10. Common Developer Pitfalls & Traps 🔝

Using System.exit(0) Instead of dispose()

Calling System.exit(0); kills all windows. Always use dispose(); to close an individual window cleanly.

NullPointerException in my_update()

Invoking my_update() before l1 is initialized throws NullPointerException. Create components before setting text.

11. Complete Compilable Java Program 🔝

public class DataTransferVerifyDemo {
    public static void main(String[] args) {
        String transfer = "First -> Second";
        if (transfer.contains("->")) {
            System.out.println("All Java Swing multi-window data transfer verification checks passed!");
        }
    }
}

Output:

All Java Swing multi-window data transfer verification checks passed!

12. Frequently Asked Questions (FAQ) 🔝

What is the difference between JFrame and JDialog for popups?

A JFrame is an independent OS window with its own taskbar icon; a JDialog is dependent on a parent window and can be made modal (blocking input to the parent until dismissed).

How do I prevent the user from opening multiple copies of the second window?

Store a reference to secondWindow in the parent class. Check if (secondWindow == null || !secondWindow.isDisplayable()) before creating a new instance.

Can I transfer non-string objects like Student records?

Yes! Pass full model objects (e.g. my_update(Student s)).

How do I pass database records fetched from MySQL to a JTable in a second window?

See JTable Tutorial and Displaying MySQL Data in JTable.

How do I save data entered in First.java into MySQL instead of passing to Second.java?

See JFrame Form to MySQL Table Tutorial.

Further Reading & Related Tutorials 🔝


Java



plus2net.com



12-07-2021

good

21-10-2021

tq ...its very usefull to me

21-10-2021

tq ...its very usefull to me



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer