Reputation: 23
I'm working on a game of hangman. I've created an array of 26 JButtons, each with a letter of the alphabet as its text. I want to grab a button's letter when it is clicked and assign it to a variable, so that it can be compared to letters in the string being guessed. Here is the code for the ActionListener and its attachment to each of the buttons in a loop ("letters" is the array of 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]);
}
}
Thanks for your help! This is my first time posting; it's for my final project for Computer Science I!
Upvotes: 2
Views: 1811
Reputation: 347334
The immediate problem I think you're having has to do with how you've desiged your 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]);
}
There is no need for the listener to extend from 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
}
}
Now, personally, I don't like doing blind casts like this...A better solution would be to use the 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
}
}
Upvotes: 3