在JComboBox中显示数组内容

时间:2016-04-12 21:23:39

标签: java swing

我有两个类,一个用于读取文件中的文本并将数据放入数组的类,而在主类中我想将数组内容添加到JComboBox中。但我收到错误“无法解决变量”任何帮助?

readfiles.java

public class readfiles {
String [] names = new String[15];
int i = 0;
public Scanner readNames;

//Opens the file
public void openFile() {
    try {
        readNames = new Scanner(new File("ChildName.txt"));
    } catch (Exception e) {
        System.out.println("Could not locate the data file!");
    }
}

//Reads the names in the file
public void readFile() {
    while(readNames.hasNext()) {
        names[i] = readNames.next();
        System.out.println(Arrays.toString(names));
        System.out.println(names[i]);
        i++;
    }
}

//Closes the file 
public void closeFile() {
    readNames.close();
}

}

Main.java

   //JComboBox for selecting child
    JLabel selectChildName = new JLabel("Please Select Your Child:");
    sPanel.add(selectChildName);
    JComboBox<String> selectChild = new JComboBox<String>(names); // (names); is the error, cannot be resolved to a variable
                sPanel.add(selectChild);

2 个答案:

答案 0 :(得分:1)

您将无法访问主要名称中的名称,因为它不在主要范围内。要访问它,请创建readfiles类的实例,然后通过执行instance.names;

来获取名称

例如,

readfiles instance = new readfiles();
instance.openfile();
instance.readfile();
instance.closefile();
JComboBox<String> selectChild = new JComboBox<String>(instance.names);

答案 1 :(得分:0)

names变量是readFiles类的变量,因此在Main类中不可见。您需要在readFiles上调用getter方法以在需要时获取数组。

相关问题