Reputation: 67
Hi I am learning java and in my project I am trying to pass a data to another JFrame.
This is my Guest Frame class
public class GuestFrame extends javax.swing.JFrame {
private List<String> list = new ArrayList<String>();
public GuestFrame(){
initComponents();
}
}
The way I am adding data to arraylist is by adding selected item from JList to the cart appended one by one like so :
private void kButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String receiveList = lstEntitety.getSelectedValue().toString();
list.add(receiveList);
//System.out.println(list.toString()); outputs all the data added
And the getter function for that list :
public List<String> getList() {
return list;
}
What I am trying to do is display all the added food in my another JFrame
public class CartFrame extends javax.swing.JFrame {
private GuestFrame food;
public CartFrame() {
initComponents();
food= new GuestFrame();
List<String> list = food.getList();
//Here I am trying to output the arraylist that I appended in prevous frame
jTextArea1.setText(list.toString());
}
The result upon stepping into CartFrame is that array seems to output empty []
I figured it might be because in Guest frame constructor is overriding it ?
I am not sure how to resolve this issue.
Upvotes: 0
Views: 2025
Reputation: 436
I think there are 3 options to solve this case,
1. may use database to manipulate the list data. so GuestFrame
is used to save data while CartFrame
can get the data from database without have dependency on other class property.
2. second, may use java.util.Properties to manipulate list data.
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("xyz.properties");
prop.load(in);
save data in GuestFrame
:
prop.setProperty("dataSize", "(list.lenght())");
prop.setProperty("data1", "...");
prop.setProperty("data2", "...");
prop.setProperty("...", "...");
....
prop.store(new FileOutputStream("xyz.properties"), null);
load data in CartFrame
:
prop.getProperty("dataSize");
//loop i=0 until < dataSize
list.add(prop.getProperty("data"+i));
3. last option is to make private List<String> list = new ArrayList<String>();
become static private static List<String> list = new ArrayList<String>();
, so then other classes can access the list property from GuestFrame
directly without need to create the instance.
public class GuestFrame extends javax.swing.JFrame {
private static List<String> list = new ArrayList<String>();
public GuestFrame(){
initComponents();
}
public static List<String> getList() {
return list;
}
}
public class CartFrame extends javax.swing.JFrame {
public CartFrame() {
initComponents();
List<String> list = GuestFrame.getList();
cText.setText(list.toString());
jLabel3.setText(list.toString());
}
}
Static property are associated to the class directly. they can be called even without creating an instance of the class, ex: ClassName.propertyName
Upvotes: 1