将数组传递给ActionListener,另一个数组触发事件

时间:2015-07-10 04:11:52

标签: java swing actionlistener

以下是我的代码。我试图创建一个包含6个随机数和30个复选框的数组。在动作监听器中,我想验证用户单击的六个框是否是我的六个随机数。但是,我无法将随机数字数组拉到actionlistener。有人可以给我一些指导吗?我对此非常感兴趣。 int [] rand数组让我感到悲伤。

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class JLottery2 extends JFrame implements ActionListener
{
   int actionCounter = 0;
   int matchTally = 0;

   final int MAXBOXES = 6; 
   final int WIDTH = 500; 
   final int HEIGHT = 200;
   JCheckBox[] boxes = new JCheckBox [30];

   public JLottery2()
   {
      super ("~*~*~ JLOTTERY 2 ~*~*~");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout (new FlowLayout());
      setSize(WIDTH, HEIGHT);

      System.out.println("Constructor");

      //great the check boxes and assign them a value      
      for (int count=0 ; count < 30; count++)
      {
         boxes[count] = new JCheckBox (Integer.toString(count));
         add(boxes[count]);
         boxes[count].addActionListener(this);
      }

      int[] rand = new int[MAXBOXES]; 
      for (int i = 0; i < MAXBOXES; i++)
      {
         rand[i] = (int)(Math.random() * 30);
         //incase it tries to generate the same random number 
         for (int j = 0; j < i; j++)
         {
            if(rand[i] == rand[j])
            {
              i--; 
            }
         }
      }


      setVisible(true);
   }

   public void actionPerformed(ActionEvent e, )
   {      
      System.out.println(rand[5]);

      if(actionCounter < MAXBOXES)
      {
         System.out.println("Action Triggered");
         Object source = e.getActionCommand();
         System.out.println(source);         
         actionCounter++;
         System.out.println(actionCounter);   
      }
      else 
      {
         System.out.println("You reached the max at " + actionCounter);
      }

   } 

   public static void main(String[] args)
   {
      JLottery2 prog = new JLottery2();
   }
}

2 个答案:

答案 0 :(得分:1)

使rand类实例字段如boxes

public class JLottery2 extends JFrame implements ActionListener
{
     //...
     JCheckBox[] boxes = new JCheckBox [30];
     int[] rand;

     public JLottery2()
     {
         //...
         rand = new int[MAXBOXES]; 

现在,这为您提供了该字段的类级别上下文,允许您从类中的任何位置进行访问

答案 1 :(得分:1)

actionPerformed方法无法访问rand,因为在rand构造函数的本地范围内声明了JLottery2。如果在全局范围内声明rand,在所有方法之外(如MAXBOXES, WIDTH, HEIGHT等),则可以访问它。请注意,您仍然可以在构造函数中初始化它:

public class JLottery2 extends JFrame implements ActionListener
{
    int actionCounter = 0;
    int matchTally = 0;
    int[] rand;
    ......
    public JLottery2()
    {
        ....
        rand = new int[MADBOXES];

编辑: Here's一个很好的链接供您查看。它用基本的Java代码解释了范围。