有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    我只是不知道你是怎么想的

    创建一系列SearchDisplay并将它们添加到滚动窗格(通过addPanel

        while (result.next()) {
            searchDisplay  = new SearchDisplay (result);            
            // nb- Bad idea
            scroll.add(searchDisplay);
            addPanel.add(searchDisplay);
        }    
        // nb- Worrisome...
        scroll.setPreferredSize(new Dimension(425,390));
        scroll.setViewportView(addPanel);
    

    然后,您似乎向某个静态对象添加了一个ActionListener

        SearchDisplay.AddToCart.addActionListener(action);
    

    有什么联系?这个AddToCart按钮如何知道应该添加什么?在这个过程中是否设置了其他static变量

    我会想象SearchDisplay的每一个实例都会有它自己的AddToCart和它自己的ActionListener知道它与哪个项目相关