如何执行JButton的actionlistener一定次数

时间:2015-01-16 22:39:39

标签: java arrays swing random actionlistener

我有一些代码,其中我有5个JButton的代码,我有一个单独的数组,生成1-6之间的随机数(骰子滚动)和动作监听器内部我只有将我的按钮添加到我的面板的部分(panel.add(roll1))并且在动作监听器之前我有一个生成随机数的数组然后我有一个开关说如果随机数是1然后将图像设置为dice1如果数组是2设置图像到dice2。所以我现在所有这一切工作,因为我正在制作yahtzee游戏我需要知道如何使每次移动最多3次运行。现在JButton只被点击一次,它输出其他JButton随机骰子图像,但当我再次点击滚动按钮按钮骰子不滚动它保持不变。你会怎么做?

public static void randomRoll(final JPanel panel) throws Exception
  {

    final ImageIcon icon = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Dice-1.png/45px-Dice-1.png"));
    final ImageIcon icon1 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Dice-2.png/45px-Dice-2.png"));
    final ImageIcon icon2 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Dice-3.png/45px-Dice-3.png"));
    final ImageIcon icon3 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Dice-4.png/45px-Dice-4.png"));
    final ImageIcon icon4 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Dice-5.png/45px-Dice-5.png"));
    final ImageIcon icon5 = new ImageIcon(new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Dice-6.png/45px-Dice-6.png"));

    final ImageIcon [] diceIcons = {icon, icon1, icon2, icon3, icon4, icon5};

    int array [] = new int [5];


    for(int i = 0; i < 5; i++)
    {
      array [i]= (int) (Math.random () * 6) + 1;
      System.out.println(array[i]);
    }

    final JButton roll1 = new JButton(diceIcons[array[0]-1]);
    final JButton roll2 = new JButton(diceIcons[array[1]-1]);
    final JButton roll3 = new JButton(diceIcons[array[2]-1]);
    final JButton roll4 = new JButton(diceIcons[array[3]-1]);
    final JButton roll5 = new JButton(diceIcons[array[4]-1]);
    final JButton dice = new JButton ("Roll Dice");

    dice.setBounds(40, 40, 100, 30);
    panel.add(dice);
    panel.setLayout(null);

    dice.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        roll1.setBounds(40, 100, 70, 70);
        roll2.setBounds(40, 180, 70, 70);
        roll3.setBounds(40, 260, 70, 70);
        roll4.setBounds(40, 340, 70, 70);
        roll5.setBounds(40, 420, 70, 70);

        //Adding to JFrame
        panel.add(roll1);
        panel.add(roll2);
        panel.add(roll3);
        panel.add(roll4);
        panel.add(roll5);
        panel.doLayout();
        panel.repaint();
        panel.revalidate();
     }
    });


  }

更新

dice.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    int array [] = new int [5];

    for(int i = 0; i < 5; i++)
    {
      array [i]= (int) (Math.random () * 6) + 1;
      System.out.println(array[i]);
    }
final JButton roll1 = new JButton(diceIcons[array[0]-1]);
final JButton roll2 = new JButton(diceIcons[array[1]-1]);
final JButton roll3 = new JButton(diceIcons[array[2]-1]);
final JButton roll4 = new JButton(diceIcons[array[3]-1]);
final JButton roll5 = new JButton(diceIcons[array[4]-1]);


    roll1.setBounds(40, 100, 70, 70);
    roll2.setBounds(40, 180, 70, 70);
    roll3.setBounds(40, 260, 70, 70);
    roll4.setBounds(40, 340, 70, 70);
    roll5.setBounds(40, 420, 70, 70);

    //Adding to JFrame
    panel.add(roll1);
    panel.add(roll2);
    panel.add(roll3);
    panel.add(roll4);
    panel.add(roll5);
    panel.doLayout();
    panel.repaint();
    panel.revalidate();
 }
});

2 个答案:

答案 0 :(得分:2)

您可以使用setActionCommand("add" + "1");将每个JButton设置为actionCommand //假设'1'是来自for循环的'i'值

然后,在ActionListiner实现的方法中:

@Override
public void actionPerformed(ActionEvent e) {

    String cmd = e.getActionCommand();

    if (cmd.equals("add1")){
        System.out.println("from add1");
    }


}

答案 1 :(得分:1)

您的随机码,

int array [] = new int [5];


for(int i = 0; i < 5; i++)
{
  array [i]= (int) (Math.random () * 6) + 1;
  System.out.println(array[i]);
}
在您的randomRoll(...)方法中调用

,但在JButton的ActionListener中调用 。如果您希望按下按钮进行随机化,则随机化代码必须位于按下按钮时触发的侦听器内。

与您的问题无关的其他问题:

  • 避免使用空布局和setBounds(...),因为这会导致无法控制的看起来很糟糕的GUI,这些都是调试或增强的负担。而是使用布局,这里GridLayout可以很好地保存你的骰子图像。
  • 你可能最好不要用JLabel而不是JButton来展示你的骰子,除非你绝对需要制作它们&#34;可按下&#34;。
  • 您需要在程序启动时将图像读入ImageIcons,并将值存储在字段中。
  • 您的randomRoll(...)方法是静态的,表明您的程序本身可能过度使用静态修饰符

注意,要将按钮数量限制为3,请将计数器放在按钮的ActionListener中,然后在计数达到3时禁用按钮,否则在计数为时退出动作侦听器大于3.例如在我的代码中,我有类似的东西:

private class ButtonAction extends AbstractAction {
  private Random random = new Random();
  private int buttonPressCount = 0;

  public ButtonAction(String name) {
     super(name);
     int mnemonic = (int) name.charAt(0);
     putValue(MNEMONIC_KEY, mnemonic);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
     // check if number of presses exceeds max
     if (buttonPressCount >= BUTTON_PRESS_TOTAL_COUNT) {
        return; // we've exceeded our max
     }
     for (JLabel jLabel : dieLabels) {
        int index = random.nextInt(dieImageList.size());
        jLabel.setIcon(dieImageList.get(index));
     }

     buttonPressCount++;

     // or do this -- disable the button
     if (buttonPressCount >= BUTTON_PRESS_TOTAL_COUNT) {
        setEnabled(false);
     }
  }
}

使用JLabel和布局管理器的示例:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class DiceRoller extends JPanel {
   private static final String BASE_PATH = "http://upload.wikimedia.org/wikipedia/commons/thumb/";
   private static final String[] DICE_PATH = {
      "c/c5/Dice-1.png/45px-Dice-1.png",
      "1/18/Dice-2.png/45px-Dice-2.png",
      "7/70/Dice-3.png/45px-Dice-3.png",
      "a/a9/Dice-4.png/45px-Dice-4.png",
      "6/6c/Dice-5.png/45px-Dice-5.png",
      "5/5c/Dice-6.png/45px-Dice-6.png"
 };
   private static final int BUTTON_PRESS_TOTAL_COUNT = 3;
   private static final int BUTTON_COUNT = 5;

   private List<Icon> dieImageList = new ArrayList<>();
   private Icon emptyIcon;
   private JLabel[] dieLabels = new JLabel[BUTTON_COUNT];

   public DiceRoller() throws IOException {
      for (String dicePath : DICE_PATH) {
         String path = BASE_PATH + dicePath;
         URL url = new URL(path);
         BufferedImage img = ImageIO.read(url);
         dieImageList.add(new ImageIcon(img));
      }

      int biWidth = dieImageList.get(0).getIconWidth();
      int biHeight = dieImageList.get(0).getIconHeight();
      BufferedImage emptyImage = new BufferedImage(biWidth, biHeight,
            BufferedImage.TYPE_INT_ARGB);
      emptyIcon = new ImageIcon(emptyImage);

      int gap = 8;
      JPanel btnPanel = new JPanel(new GridLayout(0, 1, 0, gap));
      btnPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
      for (int i = 0; i < dieLabels.length; i++) {
         dieLabels[i] = new JLabel(emptyIcon);
         btnPanel.add(dieLabels[i]);
      }

      JPanel topPanel = new JPanel();
      topPanel.add(new JButton(new ButtonAction("Roll")));

      setLayout(new BorderLayout());
      add(topPanel, BorderLayout.PAGE_START);
      add(btnPanel, BorderLayout.CENTER);
   }

   private class ButtonAction extends AbstractAction {
      private Random random = new Random();
      private int buttonPressCount = 0;

      public ButtonAction(String name) {
         super(name);
         int mnemonic = (int) name.charAt(0);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         if (buttonPressCount >= BUTTON_PRESS_TOTAL_COUNT) {
            return; // we've exceeded our max
         }
         for (JLabel jLabel : dieLabels) {
            int index = random.nextInt(dieImageList.size());
            jLabel.setIcon(dieImageList.get(index));
         }

         buttonPressCount++;

         if (buttonPressCount >= BUTTON_PRESS_TOTAL_COUNT) {
            setEnabled(false);
         }
      }
   }

   private static void createAndShowGui() {
      DiceRoller roller = null;
      try {
         roller = new DiceRoller();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      JFrame frame = new JFrame("Roll");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(roller);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}