Passing Values Between Jframes

Passing values between JFrames

First of all, your program design seems a bit off, as if you are using a JFrame for one of your windows where you should in fact be using a JDialog since it sounds as if one window should be dependent upon the other.

But regardless, you pass references of GUI objects the same as you would standard non-GUI Java code. If one window opens the other (the second often being the dialog), then the first window usually already holds a reference to the second window and can call methods off of it. The key often is when to have the first window call the second's methods to get its state. If the second is a modal dialog, then the when is easy -- immediately after the dialog returns which will be in the code immediately after you set the second dialog visible. If it is not a modal dialog, then you probably want to use a listener of some sort to know when to extract the information.

Having said this, the details will all depend on your program structure, and you'll need to tell us more about this if you want more specific help.

For a simple example that has one window open another, allows the user to enter text into the dialog windows JTextField, and then places the text in the first window's JTextField, please have a look at this:

import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class WindowCommunication {

private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");

// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;

public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);

add(field);
add(openDialogeBtn);
}

private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over

// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}

class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");

public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}

// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}

// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}

You'd do a very similar technique to get information out of a JTable.

And again, if this information doesn't help you, then please tell us more about your program including showing us some of your code. The best code to show is a small compilable example, an SSCCE similar to what I've posted above.

How to pass value between two jframes

Try This

Sample Image

import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;

class TestFrameExample extends JFrame implements ActionListener{
static JLabel label ;
public static TestFrameExample test;
TestFrameExample()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
label = new JLabel("This is a label!");
JButton button = new JButton("Open");
button.setText("Press me");
button.addActionListener(this);
panel.add(label);
panel.add(button);
add(panel);
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent a)
{
new TestFrameExample1();
}
public static void main(String s[]) {
test=new TestFrameExample();
}
}

class TestFrameExample1 extends JFrame implements ActionListener {
JTextField t;
TestFrameExample test;
public TestFrameExample1()
{
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
t=new JTextField();
t.setBounds(100,20,150,20);
JButton button=new JButton("oK");
button.setBounds(100,50,100,30);
button.addActionListener(this);
add(t);
add(button);
}
public void actionPerformed(ActionEvent a)
{
test.label.setText(t.getText());
}
}

passing information from one jframe to another

Doing this is fairly easy. All you need to do is to set a constructor in which you are passing your frame with the values you need over to your new frame.

For example, I have a LoginScreen.java and DoctorScreen.java. If my user successfully entered his details and logs in, I transfer an ArrayList of Doctors from one JFrame to another JFrame, or more precisely, from one java class to another by creating a new instance of that class

Example here

Passing an arraylist from LoginScreen.java to DoctorScreen.java

DoctorScreen dScreen = new DoctorScreen(frame, docList,d);

Now Taking those values passed from LoginScreen.java and setting them in DoctorScreen.java

public DoctorScreen(JFrame frame, ArrayList<Doctor> docList, Doctor d) {
// TODO Auto-generated constructor stub
dialog = new JFileChooser(System.getProperty("user.dir"));
this.frame = frame;
this.docList = docList;
this.d = d;
initialize();
}

Now, you can change the DoctorScreen Constructor to fit into whatever project you are trying to do.

The steps I would advise you to take is to create a Java file for handling your input, and the second Java file to display what you entered in the first file

EG:

JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String field1 = txtrEnterYourFull.getText();
String name = nameL.getText();
String field2 = txtroptionalEnterYour.getText();

Display display = new Display(name, field1, field2);//using this as example
}

}

Then in your display.java, call your constructor taking in these fields and display them either in a textfield/textarea or in a JLabel in your frame

 String name, field1, field2;

public Display(String name, String field1, String field2){

this.name = name;
this.field1 = field1;
this.field2 - field2;
}

Please take note that these variables have already been declared and I am merely using this for demonstration purposes.

Passing values between classes

UPDATE with your code.

You can take advantage of PropertyChangeListener and PropertyChangeSupport (This classes implements Observer Pattern).

I give you an example you for guidance:

public class MusicPlayerPanel extends JPanel {

private JList list;
private JButton addButton;
private PropertyChangeListener listener = new MyPropertyChangeListener();

//..in some place
addButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JFrame form = new FrameForm();
form.addPropertyChangeListener(FrameForm.BUTTON_CLICKED,listener);
form.setVisible(true);
}

});

//in another place

private class MyPropertyChangeListener implements PropertyChangeListener{

@Override
public void propertyChange(PropertyChangeEvent evt){
if(evt == null)
return;

if(evt.getPropertyName().equals(FrameForm.BUTTON_CLICKED)){
String value = (String) evt.getNewValue();
((DefaultListModel)list.getModel()).addElement(value);
}

}

}

}

And the frame form like this:

public class AddListFrame extends JFrame{

private JTextField textfield;
private JButton submitButton;
public static final String BUTTON_CLICKED ="buttonClicked";

// in some place
submitButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
firePropertyChange(BUTTON_CLICKED,null,textfield.getText());
}

});
}

Note: In java by convention, classes start with uppercase and follow a camel style. This is very important for readability.

how to pass a variable from one JFrame to another

Hi this is an approach of how you can do it, simply you need to construct a new JFrame with a constructor that recives the parameter you need.

First JFrame, where there are the buttons

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JButton;

public class Frame1 extends JFrame{

private String mensaje;
private JButton btnHola;
private JButton btnAdios;

public Frame1() {
getContentPane().setLayout(null);

btnHola = new JButton("Hello");
btnHola.setBounds(63, 210, 89, 23);
getContentPane().add(btnHola);
btnHola.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
mensaje = Frame1.this.btnHola.getText();
Frame2 frame2 = new Frame2(mensaje);
}
});

btnAdios = new JButton("Bye");
btnAdios.setBounds(245, 210, 89, 23);
getContentPane().add(btnAdios);

btnAdios.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
mensaje = Frame1.this.btnAdios.getText();
Frame2 frame2 = new Frame2(mensaje);
}
});
}

public static void main(String[] args) {
Frame1 frame = new Frame1();
frame.setVisible(true);
}
}

Second JFrame, where the message is received.

import javax.swing.JFrame;

public class Frame2 extends JFrame {
public Frame2(String message) {
super();
setVisible(true);
setTitle(message);
}
}

I hope this help you.
Greetings!

Variable stored in Session ? / passing variables between JFrames

This line

String Meno = login.Meno; 

makes me think you have something like

class Login {
public String Meno;
}

with your frame declared like

class MyFrame {
private Login login;
}

What you want is to have your Login class be the model of your application, which will distribute the changes. This means you don't have a public member, but a getter/setter methods.

class Login {
private String meno;
public void setMeno(String n) { this.meno = n; }
public String getMeno() { return meno; }
}

If you want to display that name, you can do that:

JTextField field = new JTextField(login.getMeno());

Then, because the name might change, you need a mechanism for the GUI components to update. This can be done using the listener pattern:

interface NameListener {
public void nameChanged(String newName);
}

class Login {
private String meno;
private Collection<NameListener> listeners = new ArrayList<>();
public void addListener(NameListener l) { listeners.add(l); }
public void setMeno(String n) {
meno = n;
for (NameListener l : listeners) { l.nameChanged(n); }
}
}

To enable updates in your text field, you can then do

JTextField field = new JTextField(login.getMeno());
login.addListener(n -> field.setText(n));

Since you only have one Login instance (you should use the singleton pattern), the other frame can just register as a listener like that. Here's how you declare a singleton Login class:

class Login {
private static final Login INSTANCE;
private Login() {}
public Login getInstance() {
if (INSTANCE == null) { INSTANCE = new Login(); }
return INSTANCE;
}

private String meno;
// ...
}

You can then use it in your JFrames like this:

class MyFrame {
Login login = Login.getInstance();
// ...
}


Related Topics



Leave a reply



Submit