下面是我的密码。我试图创建一个由6个随机数和30个复选框组成的数组。在动作侦听器中,我想验证用户单击的六个框恰好是我的六个随机数。但是,我不能将随机数数组拉到random侦听器。有人能给我指点吗?我在这方面完全是个新手。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();
}
}
发布于 2015-07-09 20:27:17
使rand
成为类实例字段,如boxes
public class JLottery2 extends JFrame implements ActionListener
{
//...
JCheckBox[] boxes = new JCheckBox [30];
int[] rand;
public JLottery2()
{
//...
rand = new int[MAXBOXES];
这将为字段提供一个类级别的上下文,从而允许您从类中的任何位置访问。
发布于 2015-07-09 20:27:46
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];
编辑: 下面是是一个很好的链接,供您查看。它用基本的Java代码解释作用域。
https://stackoverflow.com/questions/31332309
复制相似问题