Java Hangman项目:动作侦听器 [英] Java Hangman Project: Action Listener

查看:141
本文介绍了Java Hangman项目:动作侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个子手游戏。我使用Netbeans中的GUI工具栏将按钮A-Z如下所示:

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

我的问题是,如何我可以在其中添加动作监听器吗?是否可以使用循环?如果我单击按钮A,我将得到字符'a',依此类推。

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..

推荐答案

是的,可以使用循环,但是由于您的JButton是使用NetBeans代码生成创建的,因此它们最初不会在数组或集合中,因此,您必须执行以下操作:创建JButton数组并填充它使用NetBeans创建的按钮。然后,创建一个for循环很简单,并在该循环中添加一个在其逻辑中使用ActionEvent的actionCommand(如上所述)的ActionListener。

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.

我认为更好的解决方案是放弃使用NetBean的GUI构建器(Matisse),而是手动创建Swing代码。这将使您对代码有更大的控制权,也可以更好地理解它。例如,如果您这样做,则可以在for循环中创建按钮,添加侦听器并将按钮添加到其容器(JPanel)。

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).

例如

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

这篇关于Java Hangman项目:动作侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆