我了解如何执行此操作的基础知识。就好像我在文本文件中有以下内容:(每个数字代表一个新行,实际上不会在文件中)
- 项目1
- 项目2
- 项目3
等等,使用 this question/answer 中的示例,我可以很好地填充 JComboBox
列表。它将该行的字符串添加为组合框选项。
我的问题是我没有使用与上面类似的文本文件,而是如下所示:
- 商品1 6.00
- 商品2 8.00
- 项目3 9.00
这些数字是我稍后必须转换为双倍的价格。但从该文本文件中,价格将包含在 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
}
为了让它看起来漂亮,有一个快速但肮脏的方法:为类提供一个 toString()
方法,该方法仅打印出项目名称,例如,
@Override
public String toString() {
return itemName;
}
...或者更复杂且可能更简洁的方法:为 JComboBox 提供一个仅显示项目名称的渲染器。
编辑
你问:
Ok, just unsure how I go about passing through the values from the file.
您将解析文件并使用数据创建对象。伪代码:
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
关于java - 尝试使用文件读取器从文本文件创建 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22337053/