簡體   English   中英

當它是具有相同動作偵聽器的JButton數組時,單擊哪個Jbutton

[英]Which Jbutton is being clicked, when it is an array of JButtons with the same actionlistener

我正在為 瓷磚拼圖

我有一個Jbuttons數組,其文本設置為當前包含的數字。

我有命令

evt.getActionCommand();

這將返回jbutton中的字符串,但是我需要的是按下數組中的jbutton,因此我可以使用該值來對應我的Node類,后者使用2d數組來跟蹤Node值

新代碼歸功於充滿鰻魚的氣墊船

for (int i = 0; i < tileButtons.length; i++) {
        if (source == tileButtons[i]) {
            // the current i and j are your array row and column for the source button
            System.out.println("the " + i + " button");
        }
    }

您可以通過evt.getSource()獲得實際的按鈕。 這將返回實際按下的JButton對象。 然后,如果將按鈕固定在數組中,則可以輕松地遍歷數組,直到找到與源匹配的按鈕。

Object source = evt.getSource();
for (int i = 0; i < buttonArray.length; i++) {
   for (int j = 0; j < buttonArray[i].length; j++) { 
     if (source == buttonArray[i][j]) {
        // the current i and j are your array row and column for the source button
     }
   }
}

警告中的注意事項: ActionEvent#getSource()方法並不總是返回JButton,但會再次返回導致ActionListener觸發的原因,這可以是AbstractButton,JMenuItem,SwingTimer的任何子級,也可能是其他子級。

從該方法的參數“ e”上調用getSource()。

public void actionPerformed(ActionEvent e);

您可以使用HashMap將每個按鈕與一些自定義數據對象相關聯。 這是一個實踐該想法的測試程序。

public class ButtonTest implements ActionListener{
    public static void main(String[] args){
        new ButtonTest();
    }
    HashMap<JButton, String> buttonToLocationMap;
    public ButtonTest(){
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout());
        frame.setVisible(true);
        frame.setSize(300, 300);
        buttonToLocationMap = new HashMap<>();

        JButton button1 = new JButton("Button1");
        button1.addActionListener(this);
        buttonToLocationMap.put(button1, "Replace the value type of this hashmap with any object associated with button1");
        frame.add(button1);


        JButton button2 = new JButton("Button2");
        button2.addActionListener(this);
        buttonToLocationMap.put(button2, "Replace the value type of this hashmap with any object associated with button2");
        frame.add(button2);     
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(buttonToLocationMap.get((JButton)e.getSource()));
    }
}

暫無
暫無

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

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