I need to ask a small question because its irritating me.
How do i pass one vale from one frame to another frame in Java?
Below i have written a small script that is supposed to return the value but i dont quite know how to access it in the other frame.
Here is the code that is suppose to return the current value in a JcomboBox as a string into the other frame:
public String getUser(String user)
{
user = (String)jComboBox1.getSelectedItem().toString();
return user;
}
The way i thought it would work is to call a new instance of that class into the other frame (the classes name is editUser) so here is what i thought i would need to do.
public editPass()
{
initComponents();
editUser name = new editUser();
String test = name.getUser();
}
Thanks in advance for any advice.
The problem is that with doing this:
editUser name = new editUser()is that you are creating a new instance (besides the fact that class names should start with upper case as per convention). This causes you to loose any data since you are now referencing a new object.If you need to access data from the previous frame, what you would need to do would be to either:
As a side note, the Card Layout might be relevant to what you are trying to achieve.
EDIT:
As per your comment question:
Assuming you have an
editUserframe, say we call itframe1and you populate all the data you need.Then, the user presses Next, or something similar which causes him/her to go to the next frame, thus
frame1will either be hidden or non existant any more, depending on your implementation.Let us call the second frame
frame2. Now, inframe2you need to access details stored inframe1. Doing like so:editUser name = new editUser();will causeframe2to create a new instance offrame1, thus meaning that you have created a new frame with empty values. Callingname.getUser()should not yield anything.When I mentioned create an object with the relevant data I meant that, if you are editing user values, you could create an object which would have for instance all the information which was edited. So it could have fields like
userId,originalUserName,newUserName, etc.One the user presses Next in your
frame1, you could create and populate this object and use it to transfer data from one frame to the next. In this case, the object you would be creating would be known as a Data Transfer Object (DTO).So, the constructor of your second frame would look something like so:
And in your
editUserclass, just before creating a new instance ofeditPass, you would do something like so:Alternatively, you can pass a reference to
frame1instead of a DTO. This approach is simpler. So your constructor foreditPasswould look like this:With your
editUsercode looking like so: