Java刽子手。如何创建多个按钮和actionlisteners?

时间:2015-04-21 00:27:18

标签: java user-interface button actionlistener

我正在尝试用字母表中每个字母的按钮创建一个刽子手游戏。我使用绝对定位和多个动作滑块很难做到这一点。有什么方法可以用for循环做到这两点吗?

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

感谢任何帮助。

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




}

}

3 个答案:

答案 0 :(得分: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)我们创建一个标题为字母的按钮。因为字符实际上只是整数,所以在A&#39; A&#39;中添加1。收益率&#39; B&#39;所以,我们可以使用A&#39; + i作为一个小技巧。此外,您可以使用所有字母的数组,并执行类似letter [i]的操作。

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

免责声明:我还没有对此进行过测试,这只是让你走上正轨的好方法。

答案 1 :(得分:1)

使用布局管理器管理按钮的大小调整,不要使用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

答案 2 :(得分:1)

建议:

  • 是的,使用数组或集合,例如JButton的简单数组或List<JButton>或其具体实现,ArrayList<JButton>
  • 是的,在许多人建议的for循环中创建你的字母JButtons。
  • 但不要在那里创建特殊按钮,按钮,如重置按钮或退出按钮。
  • 为要共享的所有字母按钮创建一个AbstractAction或ActionListener类,为每个特殊JButton创建一个唯一的AbstractAction或ActionListener类
  • 使用布局管理器,但不只是一个 - 嵌套它们。例如,整个GUI可以使用BorderLayout,绘图保持BorderLayout.CENTER和SOUTH或PAGE_END位置的按钮,保存按钮的JPanels可以使用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();
   }
}