簡體   English   中英

傳遞動態創建的ArrayList <JButton> ActionListener類的索引

[英]Pass Dynamically Created ArrayList<JButton> Index to ActionListener Class

首先感謝所有貢獻者。 真是救命稻草。 也就是說,這是我的第一篇文章。

我創建了一個動態的JButton對象數組,並將ActionListener附加到該按鈕。

public void printFound(ArrayList<Customer> found)
{       
    buttons = new ArrayList();
    texts = new ArrayList();
    for(Customer temp: found)
    {
        JButton btn = new JButton("Edit");
        btn.addActionListener(new PushEdit());
        btn.setPreferredSize(new Dimension(100, 40));
        panel1.add(btn);
        buttons.add(btn);
        JTextArea text = new JTextArea(temp.toString(), 8, 80);
        text.setLineWrap(true);
        panel1.add(text);
        texts.add(text);
    }
} 

當我單擊編輯按鈕時,我希望它將“按鈕”中的“ btn”索引傳遞給ActionListener,以便可以在另一個GUI中的“ temp”中顯示值。 我認為我要么需要直接傳遞temp,要么需要傳遞“ btn”的索引以及“ found”的索引。

謝謝!

正如我從您的問題中可以理解的那樣,您想要獲取存儲在buttons ArrayList中的jbutton的索引,以執行某種操作。

為此,您可以使用setActionCommandgetActionCommand方法將String與創建的每個jbutton綁定在一起,並

所以你的代碼會像這樣

public void printFound(ArrayList<Customer> found)
{       
    buttons = new ArrayList();
    texts = new ArrayList();
    Integer index=0;
    for(Customer temp: found)
    {
        JButton btn = new JButton("Edit");
        btn.setActionCommand(index.toString());
        btn.addActionListener(new PushEdit());
        btn.setPreferredSize(new Dimension(100, 40));
        panel1.add(btn);
        buttons.add(btn);
        JTextArea text = new JTextArea(temp.toString(), 8, 80);
        text.setLineWrap(true);
        panel1.add(text);
        texts.add(text);

        index=index+1;
    }
} 

每當您想要獲取索引時

System.out.print(btn.getActionCommand());

暫無
暫無

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

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