簡體   English   中英

ActionListener不適用於所有對象

[英]ActionListener not working with all of the objects

我有一個問題,當我創建一個帶有面板的滾動面板時,我想向每個面板添加一個按鈕,當我單擊它時,它會返回產品名稱並將其放在變量中。 問題在於,只有滾動窗格中的最后一個對象面板才連接到動作偵聽器。 這是滾動面板和各個面板的代碼:

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");

我只是不確定您希望它如何工作...

創建一系列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變量?

我想這IMAGIN的每一個實例SearchDisplay將有它自己的AddToCart ,它會有它自己ActionListener它知道哪些項目是與相關...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM