我有一个定制的 JPanel itemSmallCard(String prodID, String ProductName, String Price, String Retailer)
,使用它我在另一个 JPanel 中创建了它的多个实例,并在 ActionPerformed 事件上使用不同的参数一个按钮如下:
JPanel iC = new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");
mainContentPane.add(iC);
mainContentPane.revalidate();
mainContentPane.repaint();
但是,由于所有新的 JPanel 都是使用相同的变量 iC
使用相同的代码创建的,我不知道如何从中访问特定的 JPanel 变量,因此也无法访问其事件听众。
我怎样才能实现这一目标?
最佳答案
也许创建一个 ArrayList(如果您不需要访问不基于位置的特定列表)。
ArrayList<JPanel> panels = new ArrayList<JPanel>();
或者,如果您需要访问它们,您可以创建一个“HashMap”并将您的 ID 存储在其中。
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.
希望这有帮助。
关于java - 如何访问在 java swing 中运行时实例化的对象的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56383205/