gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:21:01 26 4
gpt4 key购买 nike

下面是我得到的代码。我正在尝试创建一个由 6 个随机数和 30 个复选框组成的数组。在操作监听器中,我想验证用户单击的六个框是否恰好是我的六个随机数。但是,我无法将随机数数组拉到 Action 监听器中。有人可以给我一些指导吗?我对此完全是新手。 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();
}
}

最佳答案

使 rand 成为一个类实例字段,如 boxes

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

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

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

关于java - 将数组传递给ActionListener,另一个数组触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31332309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com