我已经浏览了互联网,但无法找到答案.
我正在使用for循环创建36个按钮,称为a1 a2等,并同时为每个按钮分配一个唯一的Action Command.
后来我想从actionPerformed(ActionEvent e)方法获取按钮的名称.
我可以让ActionCommand足够简单,但我也需要按钮的名称.
任何帮助很多appitecaited!
编辑:
这是我正在使用的代码:
String letters[] = {"0","a","b","c","d","e","f"}; JButton btn[] = new JButton[35]; int count = 0; for (int f=1; f < 7;f++){ for (int i=1; i < 7;i++){ btn[i] = new JButton(letters[f]+i,cup); System.out.println(btn[i])); mainGameWindow.add(btn[i]); btn[i].addActionListener(this); String StringCommand = Integer.toString(randomArrayNum()); btn[i].setActionCommand(StringCommand); count++; if(count == 18){ generateArray(); } } }
这为6×6网格提供了36个按钮,分别为a1-6,b1-6,c1-6等
一旦我以这种方式创建按钮,我似乎无法控制按钮,我无法分配图标或获取按钮的名称.
提前致谢
解决方法
在地图中保留按钮的参考
String letters[] = {"0","f"}; JButton btn; int count = 0; HashMap<String,JButton> buttonCache = new HashMap<String,JButton>(); for (int f=1; f < 7;f++){ for (int i=1; i < 7;i++){ btn = new JButton(letters[f]+i,cup); mainGameWindow.add(btn[i]); btn.addActionListener(this); String stringCommand = Integer.toString(randomArrayNum()); btn.setActionCommand(stringCommand); buttonMap.put(stringCommand,btn); count++; if(count == 18){ generateArray(); } } }
然后,在ActionListener中,从命令中获取按钮:
public void actionPerformed(ActionEvent e) { String command = ((JButton) e.getSource()).getActionCommand(); JButton button = buttonCache.get(command); if (null != button) { // do something with the button } }
编辑
五年后重新回答这个答案,我不知道为什么我建议使用HashMap:P
这段代码完全相同,没有第三方地图:
String letters[] = {"0","f"}; int count = 0; for (int f=1; f < 7;f++){ for (int i=1; i < 7;i++) { String stringCommand = Integer.toString(randomArrayNum()); Button btn = new JButton(letters[f]+i,cup); btn.setActionCommand(stringCommand); btn.addActionListener(this); mainGameWindow.add(btn[i]); // NOTE : I have no idea what this is for... count++; if(count == 18){ generateArray(); } } }
在ActionListener中……
public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); String command = button.getActionCommand(); // do something with the button // the command may help identifying the button... }