java ActionListener无法处理所有对象
我有一个问题,当我创建一个滚动窗格,其中的面板是对象时,我想在每个面板上添加一个按钮,当我单击它时,它将返回产品名称并将其放入变量中。问题是,只有滚动窗格中的最后一个对象面板连接到操作侦听器。以下是滚动窗格和各个面板的代码:
try{
System.out.println(sql);
ResultSet rs = data.SQL.executeQuery(sql);
String list = "";
int count=0;
while (rs.next()){
count++;
}
ResultSet result = data.SQL.executeQuery(sql);
ProductDisplayPanel.removeAll();
JPanel addPanel = new JPanel();
addPanel.setLayout(new GridLayout (count, 1));
JScrollPane scroll = new JScrollPane();
while (result.next()) {
searchDisplay = new SearchDisplay (result);
scroll.add(searchDisplay);
addPanel.add(searchDisplay);
}
scroll.setPreferredSize(new Dimension(425,390));
scroll.setViewportView(addPanel);
ProductDisplayPanel.add(scroll);
ProductDisplayPanel.revalidate();
ProductDisplayPanel.repaint();
System.out.println(list);
SearchDisplay.AddToCart.addActionListener(action);
frame.add(SearchDisplay.AddToCart);
} catch (Exception ae){
ae.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
类创建实际面板:
public SearchDisplay(ResultSet result) throws Exception{
setPreferredSize(new Dimension(500, 156));
setVisible(true);
String link = result.getString("image");
System.out.println(link);
BufferedImage icecream = ImageIO.read( new URL( "file:///"+link));
JLabel lblImage = new JLabel(new ImageIcon (icecream));
name = result.getString("Name");
JLabel lblName = new JLabel(name);
String category = result.getString("Pieces");
JLabel lblFlavour = new JLabel("Pieces: "+category);
String productID = result.getString("ProductID");
JLabel lblPrice = new JLabel("Product ID: " + productID);
String price = result.getString("Price");
JLabel lblType = new JLabel("Price: "+ price +" kr");
String age= result.getString("Age");
JLabel lblBrand = new JLabel("Age: "+age);
AddToCart = new JButton("Add to cart");
# 1 楼答案
我只是不知道你是怎么想的
创建一系列
SearchDisplay
并将它们添加到滚动窗格(通过addPanel
)然后,您似乎向某个静态对象添加了一个
ActionListener
有什么联系?这个
AddToCart
按钮如何知道应该添加什么?在这个过程中是否设置了其他static
变量我会想象
SearchDisplay
的每一个实例都会有它自己的AddToCart
和它自己的ActionListener
知道它与哪个项目相关