2

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.

Community
  • 1
  • 1
Eric
  • 373
  • 1
  • 3
  • 14

1 Answers1

5

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
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Ok, just unsure how I go about passing through the values from the file. – Eric Mar 11 '14 at 21:42
  • Thank you so much for your help, I'm sure I'll be able to figure it out from here! – Eric Mar 11 '14 at 21:47
  • Ok I got it to work! Thanks. My only issue now is figuring out how to both get the items price and edit the items price in the file (as in search for the Item name line and overwrite the price or entire line) – Eric Mar 11 '14 at 23:49
  • 1
    +1 nice answer , for more information [How to use ComboBoxes](http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html) – nachokk Mar 12 '14 at 01:34
  • job for ListCellRenderer, then JComboBox showing Item1 and listners added to JComboBox 6.00 – mKorbel Mar 12 '14 at 07:45