gpt4 book ai didi

java - 在 JComboBox 中显示数组内容

转载 作者:行者123 更新时间:2023-12-01 10:04:05 25 4
gpt4 key购买 nike

我有两个类,其中一个类读取文件中的文本并将数据放入数组中,在主类中我想将数组内容添加到 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);

最佳答案

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

例如,

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

关于java - 在 JComboBox 中显示数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36584324/

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