Eri*_*ric 2 java file-io swing jcombobox
我理解如何做到这一点的基础知识.如果我在文本文件中有以下内容:(每个数字代表一个新行,实际上不会在文件中)
依此类推,使用这个问题/答案中的例子,我可以填写一份JComboBox清单.它添加了行的字符串作为combobox选项.
我的问题是我没有使用看起来像上面的文本文件,而是看起来像这样:
这些数字是我以后必须转换为双倍的价格.但是从那个文本文件中,价格将包含在JComboBox我不想发生的事情中.有没有办法指定每一行的第一个字符串?我在文件中每行不会超过2个字符串.
您应该创建一个封装此数据的类,包括项目名称和价格,然后使用此类的对象填充JComboBox.例如,
public class MyItem {
private String itemName;
private double itemCost;
// any more fields?
public MyItem(String itemName, double itemCost) {
this. ///..... etc
}
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
为了让它显得更好,有一种快速而肮脏的方式:给类一个toString()只打印项目名称的方法,例如,
@Override
public String toString() {
return itemName;
}
Run Code Online (Sandbox Code Playgroud)
...或更复杂且可能更清晰的方式:为JComboBox提供仅显示项目名称的渲染器.
编辑
你问:
好的,只是不确定我如何通过文件传递值.
您将解析文件并使用数据创建对象.伪代码:
Create a Scanner that reads the file
while there is a new line to read
read the line from the file with the Scanner
split the line, perhaps using String#split(" ")
Get the name token and put it into the local String variable, name
Get the price String token, parse it to double, and place in the local double variable, price
Create a new MyItem object with the data above
Place the MyItem object into your JComboBox's model.
End of while loop
close the Scanner
Run Code Online (Sandbox Code Playgroud)