我正在开发一款刽子手游戏。我创建了一个包含 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]);
}
}
感谢您的帮助!这是我第一次发帖;这是我计算机科学 I 的期末项目!
最佳答案
我认为您遇到的直接问题与您设计 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
}
}
关于java - 单击时如何从 JButton 中获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13852486/