2014-10-17 130 views
0

我提出AI的tile puzzle這是被點擊的JButton,當它是Jbutton將具有相同的ActionListener

我有有它的文本設置爲它目前包含數字Jbuttons中的數組的數組。

我有命令

evt.getActionCommand(); 

將返回字符串中的一個JButton,但我需要的是在陣列中什麼的JButton被按下,這樣我就可以使用該值對應於我節點類使用二維數組來跟蹤節點值

新的代碼由於一個完整的鰻魚

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

回答

2

的您可以通過得到實際的按鈕氣墊船。這將返回被按下的實際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的任何子女,並可能其他。

+1

getClientProperty/putClientProperty對於關聯(儘管不是當前索引)也可能有用。 – user2864740 2014-10-17 22:01:40

+0

@ user2864740:非常好的一點。你可以用JButton這種方式存儲你的行號和列號。爲什麼不用這個信息發佈答案,我可以對它投票呢? – 2014-10-17 22:03:01

+0

因爲移動瓷磚我會這樣做*這種方式:D這是更多的如果想要關聯瓷磚編號等(這可能已經完成)。或者,也許這只是更改的數字.. – user2864740 2014-10-17 22:06:41

1

從方法的參數「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())); 
    } 
}