2

我正在做一个刽子手游戏。我创建了一个包含 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]);
       }
}

谢谢你的帮助!这是我第一次发帖;这是为了我的计算机科学我的最后一个项目!

4

1 回答 1

3

我认为你面临的直接问题与你如何设计你的ClickListener

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();
      checker(word, letter); //this compares with the hangman word
      setEnabled(false);//I want to disable the button after it is clicked
    }   
}


for(int i = 0; i < 26; i++)
{
    // When you do this, ClickListener is a NEW instance of a JButton with no
    // text, meaning that when you click the button and the actionPerformed
    // method is called, this.getText() will return an empty String.
    letters[i].addActionListener(new ClickListener());
    gamePanel.add(letters[i]);
}

听众无需从JButton

class ClickListener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
      letter = ((JButton)event.getSource()).getText();
      checker(word, letter); //this compares with the hangman word
      setEnabled(false);//I want to disable the button after it is clicked
    }   
}

现在,就个人而言,我不喜欢像这样进行盲投...更好的解决方案是使用该actionCommand属性...

ClickListener handler = new ClickListener();
for(int i = 0; i < 26; i++)
{
    letters[i].setActionCommand(letters[i].getText());
    letters[i].addActionListener(handler);
    gamePanel.add(letters[i]);
}

class ClickListener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
      letter = event.getActionCommand();
      checker(word, letter); //this compares with the hangman word
      setEnabled(false);//I want to disable the button after it is clicked
    }   
}
于 2012-12-13T03:37:26.957 回答