從方法的參數「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()));
}
}
getClientProperty/putClientProperty對於關聯(儘管不是當前索引)也可能有用。 – user2864740 2014-10-17 22:01:40
@ user2864740:非常好的一點。你可以用JButton這種方式存儲你的行號和列號。爲什麼不用這個信息發佈答案,我可以對它投票呢? – 2014-10-17 22:03:01
因爲移動瓷磚我會這樣做*這種方式:D這是更多的如果想要關聯瓷磚編號等(這可能已經完成)。或者,也許這只是更改的數字.. – user2864740 2014-10-17 22:06:41