gpt4 book ai didi

java - 单击时如何从 JButton 抓取文本?

转载 作者:行者123 更新时间:2023-12-04 05:19:12 25 4
gpt4 key购买 nike

我正在做一个刽子手游戏。我创建了一个包含 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属性(property)...
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com