我正在做一个刽子手游戏。我创建了一个包含 26 个 JButton 的数组,每个 JButton 都有一个字母作为其文本。我想在单击按钮时获取按钮的字母并将其分配给变量,以便可以将其与被猜测的字符串中的字母进行比较。下面是 ActionListener 的代码及其与循环中每个按钮的附件(“字母”是 JButton 数组)。
public class Hangman extends JFrame
{
private JButton[] letters = new JButton[26];
private String[] alphabet = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"};
//letters are assigned to JButtons in enhanced for loop
private String letter;
class ClickListener extends JButton implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//this is where I want to grab and assign the text
letter = this.getText();
//I also want to disable the button upon being clicked
}
}
for(int i = 0; i < 26; i++)
{
letters[i].addActionListener(new ClickListener());
gamePanel.add(letters[i]);
}
}
谢谢你的帮助!这是我第一次发帖;这是为了我的计算机科学我的最后一个项目!