Domanda

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
  2. Item2
  3. Item3

and so on, using the example from this question/answer, I could populate a JComboBox list fine. It adds the line's string as a combobox option.

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
  2. Item2 8.00
  3. Item3 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. 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.

È stato utile?

Soluzione

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. e.g.,

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, e.g.,

@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.


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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top