Data transfer within JFrames

SWING Part 1, adding Button

Transferring data from one window to other.

We will create two JFrams and name then as First.java and second.java. In the first JFrame ( First.java ) we will keep one textbox and one button. In the second JFrame ( Second.java ) we will keep one JLabel to display the data we entered in our first window ( First.java ).

Create one Project

Crate a project and name it as data_transfer.

Create first.java

File > new > other > JFrame 
Give the name as First.java

Create second.java

File > new > other > JFrame 
Give the name as Second.java

Adding components

To our first.java we will go to design mode.
  1. Add absolute Layout
  2. Move to Components and Add one JTextField ( variable name t1 )
  3. Add one JButton ( variable name b1 and change the text on it to Submit )
Swing First window
To our Second.java we will go to design mode
  1. Add absolute Layout
  2. Move to Components to add one JLabel ( variable name l1 )
Swing Second window
Come to the source mode of Second.java and add the method my_update() to it. This method will receive one string variable and then assign it to JLabel l1.

public void my_update(String str) {
		l1.setText(str);
	}
In order to assign data to l1 we have to change l1 as global variable and remove the declaration inside class Second.
private JLabel l1; // add this line to set it global.

First.java

Come to design mode for first.java and double click the JButton to add ActionListener() to it.
Let us first collect the text written at JTextField t1 and store it in a string variable. Then create one object for class Second and using the same pass the string variable to my_update() method.
public void actionPerformed(ActionEvent e) {
	String str=t1.getText(); // read the JTextFeild t1 data
	Second obj= new Second();// obj created for class Second()
	obj.my_update(str);//Execute the method my_update to pass str
	obj.setVisible(true); // Open the Second.java window
	dispose(); // Close the First.java window
	}
While doing this we will open the Second.java window by setting obj.setVisible(true) and close the First.java window by using dispose();.

Execute the files. Now what ever data you enter in textfield of first.java window, will get passed to second.java window through my_update() method and first.java window will close.


swing

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    12-07-2021

    good

    21-10-2021

    tq ...its very usefull to me

    21-10-2021

    tq ...its very usefull to me

    Post your comments , suggestion , error , requirements etc here




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