1

I have a custom made JPanel itemSmallCard(String prodID, String productName, String price, String retailer), using this I created multiple instances of it in another JPanel with different parameters on the ActionPerformed event of a button as follows:

JPanel iC = new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");
        mainContentPane.add(iC);
        mainContentPane.revalidate();
        mainContentPane.repaint();

However as all the new JPanels were created with this same code using the same variable iC, I don't know how to access a particular JPanel variable from them, thus also unable to access its event listeners. How can I achieve that?

Aditya
  • 126
  • 9

2 Answers2

1

Perhaps create an ArrayList (if you don't need to access specific ones not based on location).

ArrayList<JPanel> panels = new ArrayList<JPanel>();

Or, if you need to access them, you could make a "HashMap" and store the ID you have in there.

WeakHashMap<String, JPanel> panels = new WeakHashMap<String, JPanel>();

panels.put("123456789ab", new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");// Adds a product with that info

panels.get("123456789ab"); // Returns the panel with that ID.

Hope this helps.

FeaturedSpace
  • 479
  • 3
  • 18
1

You need to write a generic listener:

  1. in the listener code you use the getSource() method to get the source of the event.
  2. Once you know the source component you can use the getParent() method of the component.
  3. Now you have access to the panel and you can access any method/variable of the panel.
camickr
  • 321,443
  • 19
  • 166
  • 288