单击时如何从JButton中获取文本?

时间:2012-12-13 03:30:09

标签: java swing jbutton

我正在做一个刽子手游戏。我已经创建了一个包含26个JButton的数组,每个JButton都有一个字母作为文本字母。我想在点击它时抓住一个按钮的字母并将其分配给一个变量,这样就可以将它与被猜测的字符串中的字母进行比较。下面是ActionListener的代码及其对循环中每个按钮的附件(“letters”是JButtons的数组)。

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

感谢您的帮助!这是我第一次发帖;这是我最后的计算机科学项目I!

1 个答案:

答案 0 :(得分: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
    }   
}