java - 尝试使用文件读取器从文本文件创建 JComboBox

标签 java swing file-io jcombobox

我了解如何执行此操作的基础知识。就好像我在文本文件中有以下内容:(每个数字代表一个新行,实际上不会在文件中)

  1. 项目1
  2. 项目2
  3. 项目3

等等,使用 this question/answer 中的示例,我可以很好地填充 JComboBox 列表。它将该行的字符串添加为组合框选项。

我的问题是我没有使用与上面类似的文本文件,而是如下所示:

  1. 商品1 6.00
  2. 商品2 8.00
  3. 项目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/

相关文章:

c++ - 如何从文件中读取特征矩阵?

java - 在 JMenu 组件中设置标题文本的对齐方式

python - fileno() 可以返回文件包装对象的句柄而不是实际文件吗?

java - Java 中的优先级队列?

java - 如何保持对在子线程上创建的实例的引用

Java-单击按钮时更改标签文本

java swing不会显示

c++ - 文件 I/O 未读入任何内容

java - 如何在 Hibernate 中进行映射

java - 部分加载具有不同编码的大文本文件