Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Hangman Project: Action Listener

I am creating a hangman game. I made a button A - Z using the GUI Toolbars in Netbeans as follows:. enter image description here

My problem is, how can I add an actionlistener to all of it. Is it possible to use a loop? If i click the button A, i will get the character 'a' and so on..

like image 900
newbie Avatar asked Dec 22 '22 18:12

newbie


2 Answers

Yes it is possible to use a loop, but since your JButtons were created by using NetBeans code-generation, they won't be in an array or collection initially, and so this is something that you'll have to do: create an array of JButton and fill it with the buttons created by NetBeans. Then it's a trivial matter to create a for loop and in that loop add an ActionListener that uses the ActionEvent's actionCommand (as noted above) in its logic.

Having said this, I think that the better solution is to forgo use of the NetBean's GUI builder (Matisse) and instead to create your Swing code by hand. This will give you much greater control over your code and a much better understanding of it as well. For instance, if you do it this way, then in your for loop you can both create your buttons, add the listeners, and add the button to its container (JPanel).

e.g.,

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

public class Foo2 {
    public static void main(String[] args) {
        JPanel buttonContainer = new JPanel(new GridLayout(3, 9, 10, 10));
        List<JButton> letterButtons = new ArrayList<JButton>(); // *** may not even be necessary
        for (char buttonChar = 'A'; buttonChar <= 'Z'; buttonChar++) {
            String buttonText = String.valueOf(buttonChar);
            JButton letterButton = new JButton(buttonText);
            letterButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String actionCommand = e.getActionCommand();
                    System.out.println("actionCommand is: " + actionCommand);
                    // TODO fill in with your code
                }
            });

            buttonContainer.add(letterButton);
            letterButtons.add(letterButton);
        }

        JOptionPane.showMessageDialog(null, buttonContainer);
    }
}
like image 195
Hovercraft Full Of Eels Avatar answered Dec 24 '22 07:12

Hovercraft Full Of Eels


Well, with some pseudo code, wouldn't this make sence for you?

for(button in bord) {
    button.addActionListener(my_actionlistener);
}

Then in your actionlistener you can see which button was pressed

public void actionPerformed(ActionEvent e) {
    // button pressed
    if ("string".equals(e.getActionCommand()) {
         // do something 
    }
    // and so forth
}
like image 26
Johan Sjöberg Avatar answered Dec 24 '22 06:12

Johan Sjöberg