【问题标题】:Java hangman. How to create multiple buttons and actionlisteners?爪哇刽子手。如何创建多个按钮和动作监听器?
【发布时间】:2015-06-27 22:33:11
【问题描述】:

我正在尝试为字母表中的每个字母创建一个带有按钮的刽子手游戏。我用绝对定位和多个 actionlisteners 完成了这件事。有什么方法可以同时使用 for 循环吗?

另外,我如何使用多态数组来实现我的刽子手?按照我现在的方式,我将为每个肢体使用一个 if 语句。我很想在他自己的面板上创建这个人,然后将每个 limg 的可见性设置为 true,因为使用时猜测失败。

感谢任何帮助。

public class HangmanGui extends JFrame{
    private JLabel headerLabel;
    private JPanel man;
    private Graphics gobj;

    private JButton aButton ;
    private JButton bButton ;
    private JButton cButton ;
    private  JButton dButton ;
    private  JButton eButton ;
    private  JButton fButton ;
    private  JButton gButton ;
    private  JButton hButton ;
    private  JButton iButton ;
    private  JButton jButton ;
    private  JButton kButton ;
    private  JButton lButton ;
    private  JButton mButton ;
    private  JButton nButton ;
    private  JButton oButton ;
    private  JButton pButton ;
    private  JButton qButton ;
    private  JButton rButton ;
    private  JButton sButton ;
    private  JButton tButton ;
    private  JButton uButton ;
    private  JButton vButton ;
    private  JButton wButton ;
    private  JButton xButton ;
    private  JButton yButton ;
    private  JButton zButton ;
    private  JButton newWButton ;
    private JButton showWButton ;
    private  JButton quitButton ;
    private  JButton startButton ;

    private JLabel blankWord;

    private JLabel titleWord;

    private JFrame frame;
    private JPanel hangman;
    private FlowLayout layout;
    private Container container;



    /*  
    public static void main (String[] args){
        GUITest gui = new GUITest();

        gui.setSize(800,900);
        gui.setVisible(true);

    }
 */ 
     //
    //   public GUITest()
   //  {



   //  }



    public HangmanGui(){
        buildGui();

    }





    public void buildGui(){
        frame = new JFrame();
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setBackground(Color.WHITE);
        frame.setBounds(100, 100, 450, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        Font lblFont= new Font("Serif", Font.BOLD, 30); 
         JLabel[] uscore = new JLabel[15];

        Man man = new Man();

        titleWord = new JLabel("A Game of Hangman.");
        titleWord.setBounds(260,10,500,150);
        titleWord.setFont(lblFont);


        add(titleWord);
    //  add(blankWord);
        //frame.add(man);
        this.add(man);
        man.setBounds(100,100,400,400);
        JPanel panel = new JPanel();


        panel.setBounds(6, 232, 400, 400);
        frame.getContentPane().add(panel);



        layout = new FlowLayout();
         container = getContentPane();
         setLayout(null);


         aButton = new JButton("A");

         add(aButton);
         aButton.setBounds(30, 520, 50, 29);
        aButton.addActionListener(
                 new ActionListener()
                 {
                 @Override
                    public void actionPerformed(ActionEvent event)
                    {

                    }
                 }
                 );



           bButton = new JButton("B");
         add(bButton);
        bButton.setBounds(80, 520, 50, 29);
        bButton.addActionListener(
                 new ActionListener()
                 {
                 @Override
                    public void actionPerformed(ActionEvent event)
                    {

                    }
                 }
                 );
        cButton = new JButton("C");
     add(cButton);
    cButton.setBounds(130, 520, 50, 29);
    cButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    dButton = new JButton("D");
     add(dButton);
     dButton.setBounds(180, 520, 50, 29);
    dButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       eButton = new JButton("E");
     add(eButton);
    eButton.setBounds(230, 520, 50, 29);
    eButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    fButton = new JButton("F");
     add(fButton);
     fButton.setBounds(280, 520, 50, 29);
    fButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       gButton = new JButton("G");
     add(gButton);
    gButton.setBounds(330, 520, 50, 29);
    gButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    hButton = new JButton("H");
     add(hButton);
     hButton.setBounds(380, 520, 50, 29);
    hButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       iButton = new JButton("I");
     add(iButton);
    iButton.setBounds(430, 520, 50, 29);
    iButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    jButton = new JButton("J");
     add(jButton);
     jButton.setBounds(480, 520, 50, 29);
    jButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       kButton = new JButton("K");
     add(kButton);
    kButton.setBounds(530, 520, 50, 29);
    kButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    lButton = new JButton("L");
     add(lButton);
     lButton.setBounds(580, 520, 50, 29);
    lButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       mButton = new JButton("M");
     add(mButton);
    mButton.setBounds(630, 520, 50, 29);
    mButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    nButton = new JButton("N");
     add(nButton);
     nButton.setBounds(680, 520, 50, 29);
    nButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       oButton = new JButton("O");
     add(oButton);
    oButton.setBounds(30, 550, 50, 29);
    oButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    pButton = new JButton("P");
     add(pButton);
     pButton.setBounds(80, 550, 50, 29);
    pButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       qButton = new JButton("Q");
     add(qButton);
    qButton.setBounds(130, 550, 50, 29);
    qButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    rButton = new JButton("R");
     add(rButton);
     rButton.setBounds(180, 550, 50, 29);
    rButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       sButton = new JButton("S");
     add(sButton);
    sButton.setBounds(230, 550, 50, 29);
    sButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    tButton = new JButton("T");
     add(tButton);
     tButton.setBounds(280, 550, 50, 29);
    tButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       uButton = new JButton("U");
     add(uButton);
    uButton.setBounds(330, 550, 50, 29);
    uButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    vButton = new JButton("V");
     add(vButton);
     vButton.setBounds(380, 550, 50, 29);
    vButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       wButton = new JButton("W");
     add(wButton);
     wButton.setBounds(430, 550, 50, 29);
    wButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    xButton = new JButton("X");
     add(xButton);
     xButton.setBounds(480, 550, 50, 29);
    xButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
       yButton = new JButton("Y");
     add(yButton);
     yButton.setBounds(530, 550, 50, 29);
    yButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
    zButton = new JButton("Z");
     add(zButton);
     zButton.setBounds(580, 550, 50, 29);
    zButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );

     startButton = new JButton("Start Game");
     add(startButton);
     startButton.setBounds(100, 700, 120, 29);
    startButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );

     newWButton = new JButton("New Word");
     add(newWButton);
     newWButton.setBounds(250, 700, 120, 29);
    newWButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );
     showWButton = new JButton("Show Word");
     add(showWButton);
     showWButton.setBounds(400, 700, 120, 29);
    showWButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );

     quitButton = new JButton("Quit Game");
     add(quitButton);
     quitButton.setBounds(550, 700, 120, 29);
    quitButton.addActionListener(
             new ActionListener()
             {
             @Override
                public void actionPerformed(ActionEvent event)
                {

                }
             }
             );



}

}

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;


public class Man extends JPanel {

     protected void paintComponent(Graphics g ){
                super.paintComponent(g);


       //gallows
           g.fillRect(10, 250, 150, 20);
           g.fillRect(40,70,10,200);
           g.fillRect(40,70,60,10);
           g.setColor(Color.yellow);
           g.fillRect(95,70,5,25);
          //head
           g.setColor(Color.black);
           g.drawOval(82,95,30,30);

           //body
           g.drawLine(97,125,97,150);
          //left leg
           g.drawLine(97,150,117,183);
           //right leg
          g.drawLine(97,150,77,183);
           // right arm
           g.drawLine(97,125,117,135);
           //left arm
           g.drawLine(97,125,77,135);




}

}

【问题讨论】:

  • "how can I implement my hangman using a polymorphic array?" -- 什么是“多态数组”?我从来没有听说过这个词,也不知道你的意思。为什么不只使用数组?说一个 JButton 数组——JButton[]?当你尝试这个时发生了什么?
  • 对不起。这是我的教授抛出的一个术语。根据我的教授的说法,多态数组存储对象的不同状态。像 Speak 超类一样吠叫、喵喵叫或咆哮。
  • 每个JButton 实例都有自己的状态,所以一个简单的数组就足够了
  • 是的,但那会是什么样子?我会使用 for 循环吗?
  • 是的,使用 for 循环。

标签: java user-interface button actionlistener


【解决方案1】:

你可以试试这样的:

// create a JPanel to hold the buttons that uses a GridLayout with 3 rows
JPanel buttonPanel = new JPanel(new GridLayout(3, ));
for (int i = 0; i < 26; ++i)
{
    wButton = new JButton('A' + i);
    buttonPanel.add(wButton);
    // wButton.setBounds(30 + i * 50, 550, 50, 29); // avoid this
    wButton.addActionListener(
        new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {

            }
        }
    );
}
// here add the buttonPanel to the main GUI

分解:

1) 我们使用 for 循环遍历字母表中的 26 个字母。

2) 我们创建一个标题为字母的按钮。因为字符实际上只是整数,所以将 1 加到 'A' 会产生 'B'。所以,我们可以使用 'A'+i 作为一个小技巧。此外,您可以使用所有字母的数组,并在那里执行诸如 letter[i] 之类的操作。

3) 避免使用 setBounds,而是使用布局管理器来更轻松、更简单地放置按钮并调整其大小。

免责声明:我没有实际测试过这个,它只是为了让你走上正轨。

【讨论】:

  • 设置边界?来吧,请不要这样。如果您要向新手推荐,请将其作为有价值的有用推荐,例如使用 JPanel 将 JButtons 放置在 GridLayout 中。
  • @HovercraftFullOfEels 我刚刚按照他们的要求使用 for 循环重新创建了 OP 的代码。我没有评论这是多么“正确”。
  • 那么我在你的帖子中指出它缺乏正确性。请改进建议。
  • 嗯,它做了一些事情。不幸的是,这个按钮已经占据了整个屏幕。
  • 我冒昧地改进了您的答案,从而允许我删除我的反对票并给您赞成票。是的,我是个坚持不懈的人,但如果我们鼓励原始发布者坚持使用 null 布局和 setBounds,他将创建非常难看的僵化、非常不灵活的 GUI,虽然它们在一个平台上看起来不错,但在大多数其他平台上看起来很糟糕,或者屏幕分辨率,并且很难更新和维护。
【解决方案2】:

使用布局管理器来管理按钮的大小,不要使用setBounds()。您当前创建了一个,但没有设置它,所以它没有被使用。

layout = new FlowLayout();
setLayout(null); // Why set null and not layout

正确设置布局,然后您可以在 for 循环中使用 char,例如

for(char c = 'A'; c <= 'Z'; c++)
{
    JButton button = new JButton("" + c);
    // add action listener also
    add(button); // adding will add it using the layout manager
}

您可以了解更多关于layout managers here的信息。

【讨论】:

    【解决方案3】:

    建议:

    • 是的,使用数组或集合,例如简单的 JButton 数组或 List&lt;JButton&gt; 或其具体实现,ArrayList&lt;JButton&gt;
    • 是的,按照许多人的建议,在 for 循环中创建您的字母 JButton。
    • 但不要在那里创建特殊按钮,例如重置按钮或退出按钮。
    • 为所有要共享的字母按钮创建一个 AbstractAction 或 ActionListener 类,并为每个特殊 JButton 创建一个唯一的 AbstractAction 或 ActionListener 类
    • 使用布局管理器,而不仅仅是一个 - 嵌套它们。例如,整个 GUI 可以使用 BorderLayout,绘图保持 BorderLayout.CENTER,按钮位于 SOUTH 或 PAGE_END 位置,持有按钮的 JPanel 可以使用 JPanel 保持在 BoxLayout 中,GridLayout 中的字母按钮使用 JPanel专业按钮也是如此。
    • 使用单独的 JPanel 绘制刽子手图像。将其逻辑与其他一切分开。它只关心猜错字母的数量,然后它应该根据这个值绘制适当的图像。所以我会给它一个增加这个数字的公共方法以及一个重置数字及其绘图的公共方法。

    例如

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.*;
    
    public class LayoutFoo extends JPanel {
    
       // using a List of JButtons to hold my collection
       private List<JButton> letterButtons = new ArrayList<>();
       private DrawingPanel drawingPanel = new DrawingPanel();
    
       public LayoutFoo() {
          JPanel letterButtonPanel = new JPanel(new GridLayout(3, 0, 3, 3));
          letterButtonPanel.setBorder(BorderFactory.createTitledBorder("Letters"));
          ButtonListener buttonListener = new ButtonListener();
          for (char c = 'A'; c <= 'Z'; c++) {
             String text = String.valueOf(c);
             JButton button = new JButton(text);
             button.addActionListener(buttonListener);
             letterButtons.add(button); // add JButton to List<JButton>
             letterButtonPanel.add(button);  // and add to GridLayout-using JPanel
          }
    
          // JPanel to hold non-letter JButtons
          JPanel specialBtnsPanel = new JPanel(new GridLayout(1, 0, 3, 3));
          specialBtnsPanel.add(new JButton(new ResetAction("Reset", KeyEvent.VK_R)));
          specialBtnsPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
    
    
          // JPanel to hold non-drawing JPanels. It uses BoxLayout
          JPanel bottomPanel = new JPanel();
          bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
          bottomPanel.add(letterButtonPanel);
          bottomPanel.add(specialBtnsPanel);
    
          // set layout and border of main JPanel and add other JPanels to it
          setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
          setLayout(new BorderLayout(3, 3));
          add(drawingPanel, BorderLayout.CENTER);
          add(bottomPanel, BorderLayout.PAGE_END);
       }
    
       private class ButtonListener implements ActionListener {
          @Override
          public void actionPerformed(ActionEvent e) {
             System.out.println("Button pressed: " + e.getActionCommand());
             ((AbstractButton) e.getSource()).setEnabled(false);
          }
       }
    
       private class ResetAction extends AbstractAction {
          public ResetAction(String name, int mnemonic) {
             super(name);
             putValue(MNEMONIC_KEY, mnemonic);
          }
    
          @Override
          public void actionPerformed(ActionEvent e) {
             for (JButton button : letterButtons) {
                button.setEnabled(true);
             }
          }
       }
    
       private class ExitAction extends AbstractAction {
          public ExitAction(String name, int mnemonic) {
             super(name);
             putValue(MNEMONIC_KEY, mnemonic);
          }
    
          @Override
          public void actionPerformed(ActionEvent e) {
             Component component = (Component) e.getSource();
             Window win = SwingUtilities.getWindowAncestor(component);
             win.dispose();
          }
       }
    
       private static void createAndShowGui() {
          LayoutFoo mainPanel = new LayoutFoo();
    
          JFrame frame = new JFrame("LayoutFoo");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    class DrawingPanel extends JPanel {
       private static final int PREF_W = 500;
       private static final int PREF_H = PREF_W;
       private int wrongLetterCount = 0;
    
       public DrawingPanel() {
          setBorder(BorderFactory.createTitledBorder("Hang Man"));
       }
    
       @Override
       public Dimension getPreferredSize() {
          if (isPreferredSizeSet()) {
             return super.getPreferredSize();
          }
          return new Dimension(PREF_W, PREF_H);
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
    
          // TODO: draw hangman here based on wrong letter count!
       }
    
       public void incrementWrongLetterCount() {
          wrongLetterCount++;
          repaint();
       }
    
       public void reset() {
          wrongLetterCount = 0;
          repaint();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-07
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2012-04-25
      • 2023-04-06
      • 1970-01-01
      • 2017-03-08
      • 2013-04-25
      相关资源
      最近更新 更多