I am creating a hangman game that uses a virtual keyboard for input. I created the keyboard layout using a for loop to create the buttons which then get put into a JButton ArrayList. All of the buttons make use of one ActionListener.
At the end of the game I need to reset all the buttons so they no longer have a border (A green or red border is placed around them during the game if the player guesses correctly). I have tried to loop through the JButton ArrayList to change the border but it only does it for the last button that was pressed. Is there a way that I can do this?
I also would like to know how to get the button back to it's original design, as when I use button.setBorder(null)
it makes the button basically disappear. I would like to remove the MatteBorder
I set earlier in the program.
public void createKeyboard() {
String buttonLabel;
char buttonLabelChar;
for (char c = 'A'; c <= 'Z'; c ++) {
buttonLabelChar = c;
buttonLabel = "" + buttonLabelChar;
JButton button = new JButton(buttonLabel);
keyboardArray = new ArrayList<JButton>();
keyboardArray.add(button);
button.setPreferredSize(new Dimension(40, 40));
pnlKeyboard.add(button);
button.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
hm.setLetterGuessed(event.getActionCommand().charAt(0));
hm.revealLetter();
if (hm.revealLetter()) {
button.setBorder(new MatteBorder(4, 4, 4, 4, Color.GREEN));
button.setEnabled(false);
}
else {
button.setBorder(new MatteBorder(4, 4, 4, 4, Color.RED));
button.setEnabled(false);
hm.loseLife();
setImage();
}
if (hm.winCheck()) {
JOptionPane.showMessageDialog(mainFrame, "You win!", "Game Over",
JOptionPane.INFORMATION_MESSAGE, new ImageIcon(Hangman.class.getResource("images/11rightleg.png")));
for (int i = 0; i < keyboardArray.size(); i ++) { // THIS DOESN'T WORK
button.setBorder(null);
}
}
else if (hm.getLives() == 0) {
JOptionPane.showMessageDialog(mainFrame, "You lose :(", "Game Over",
JOptionPane.INFORMATION_MESSAGE, new ImageIcon(Hangman.class.getResource("images/11rightleg.png")));
}
setWord();
}
}
);
}
}