Java Hangman Project: Action Listener

I create a hangman game. I made the AZ button using the Netbeans GUI toolbars as follows :.enter image description here

My problem is how can I add an actionlistener to all of this. Is it possible to use a loop? If I press the button A, I will get the character "a", etc.

+4
source share
3 answers

, , JButtons NetBeans, , , : JButton , NetBeans. for ActionListener, ActionEvent actionCommand ( ) .

, , GUI NetBean (Matisse) Swing . . , , for , (JPanel).

.

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);
    }
}
+5

, - , ?

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

,

public void actionPerformed(ActionEvent e) {
    // button pressed
    if ("string".equals(e.getActionCommand()) {
         // do something 
    }
    // and so forth
}
+3

- , , Netbeans , .

, . , ascii, 97 a 65 A:

int charNum = 97;
for(Button b : board) {
    char charVal = (char)charNum;
    charNum++;
    //add the action listener
}
+3

All Articles