在 for 循环中创建一个对象,并尝试在其他地方访问它

Creating an object in a for loop, and trying to access it elsewhere

我正在尝试创建一个程序来随机播放音乐。我已经导入了所有歌曲,现在我正在尝试为每首歌曲创建一个``JCheckBox。我有一个创建这些复选框的 for 循环,但我需要一种方法来测试该框是否被选中。我已经在使用 if(box.isSelected()),但需要辨别哪个框,并且需要在 for 循环之外访问框。 这是我的代码。 顺便说一下,songs 是一个 ArrayList

public static void checkboxList() {
    ArrayList<JCheckBox> checkboxes = new ArrayList<>();

    for (String element : songs) {
        System.out.println("Reached checkbox thing");
        System.out.println(element);
        JCheckBox box = new JCheckBox(element);
        checkboxes.add(box);
        panel.add(box);
        frame.pack();
    }
    int loop = 0;
    while (loop == 0) {
        if (checkboxes.contains(box.isSelected())) {

        }
    }
}

如果您需要唯一标识符,为什么不创建您自己的 JCheckbox?

类似于:

 public class MyCheckBox extends JCheckBox {

 public MyCheckBox(paramOne, paramTwo, paramN) {
     super();    
    //do stuff with the unique identifiers 
 }

 //inherit all methods from super class
 @Override
 public boolean isSelected() {
     return super.isSelected();
 }

  //ETC...
 }

正如大家所说,您可以添加一个事件侦听器来识别生成事件的对象。

public class evttest implements ItemListener{

//Declared your arraylist checkboxes global. To access it in other part of code
static ArrayList<JCheckBox> checkboxes ;

public evttest(){

...

checkboxList();
//After calling checkboxesList() call add method to add itemlistener to each of them
this.add();
}


public static void checkboxList() {
checkboxes = new ArrayList<>();
JCheckBox box;

for (String element : songs) {
    System.out.println("Reached checkbox thing");
    System.out.println(element);
    box = new JCheckBox(element);

    checkboxes.add(box);
    panel.add(box);
    frame.pack();
}

frame.getContentPane().add(panel);
}

//this method adds ItemListener to all the 
//checkboxes you have in your ArrayList checkboxes
public void add(){
    for(JCheckBox cb : checkboxes){
        cb.addItemListener(this);
    }
}



@Override
public void itemStateChanged(ItemEvent e) {

    //If the item is selected then do something
    if(e.getStateChange() == ItemEvent.SELECTED){

        //cb is the checkbox on which your event occured.
        //You can then use cb to perform your required operation

        JCheckBox cb = (JCheckBox)e.getSource();
        System.out.println("clicked item is: " + cb.getText());
    }
}

public static void main(String...args){
    new evttest();
    }


}