繁体   English   中英

尝试使用文件阅读器从文本文件创建JComboBox

[英]Attempting to create a JComboBox from a text file by using a file reader

我了解如何进行此基础操作。 就像在文本文件中包含以下内容一样:(每个数字代表一个新行,实际上不在文件中)

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

依此类推,使用此问题/答案中的示例,我可以很好地填充JComboBox列表。 它将行的字符串添加为combobox选项。

我的问题是我没有使用看起来像上面的文本文件,而是看起来像这样:

  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提供仅显示项目名称的渲染器。


编辑
你问:

好的,只是不确定我如何通过文件中的值。

您将解析文件并使用数据创建对象。 伪代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM