简体   繁体   English

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

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

I understand how to do the basics of this. 我了解如何进行此基础操作。 As in if I had the following in a text file: (each number represents a new line, wouldn't actually be in the file) 就像在文本文件中包含以下内容一样:(每个数字代表一个新行,实际上不在文件中)

  1. Item1 项目1
  2. Item2 项目2
  3. Item3 项目3

and so on, using the example from this question/answer , I could populate a JComboBox list fine. 依此类推,使用此问题/答案中的示例,我可以很好地填充JComboBox列表。 It adds the line's string as a combobox option. 它将行的字符串添加为combobox选项。

My issue is that I'm not using a text file that looks like the one above, instead it looks like this: 我的问题是我没有使用看起来像上面的文本文件,而是看起来像这样:

  1. Item1 6.00 项目1 6.00
  2. Item2 8.00 第2项8.00
  3. Item3 9.00 项目3 9.00

the numbers being prices I'd have to convert to a double later on. 这些价格就是我以后必须转换为两倍的价格。 But from that text file the price would be included in the JComboBox , something I don't want to happen. 但是从该文本文件中,价格将包含在JComboBox ,这是我不想发生的事情。 Is there a way to specify the first String of each line? 有没有一种方法可以指定每行的第一个字符串? I won't have more than 2 strings per line in the file. 文件中每行不会有超过2个字符串。

You should create an class that encapsulates this data including the item name and price, and then populate your JComboBox with objects of this class. 您应该创建一个封装此类数据(包括商品名称和价格)的类,然后使用该类的对象填充JComboBox。 eg, 例如,

public class MyItem {
  private String itemName;
  private double itemCost;
  // any more fields?

  public MyItem(String itemName, double itemCost) {
    this. ///.....  etc
  }  

  // getters and setters
}

To have it appear nice, there's a quick and dirty way: give the class a toString() method that prints out just the item name, eg, 为了使它看起来不错,有一种快速而肮脏的方法:给该类一个toString()方法,该方法只打印出项目名称,例如,

@Override
public String toString() {
  return itemName;
}

... or a more involved and probably cleaner way: give the JComboBox a renderer that shows only the item name. ...或更复杂,更干净的方法:为JComboBox提供仅显示项目名称的渲染器。


Edit 编辑
You ask: 你问:

Ok, just unsure how I go about passing through the values from the file. 好的,只是不确定我如何通过文件中的值。

You would parse the file and create objects with the data. 您将解析文件并使用数据创建对象。 Pseudo code: 伪代码:

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