简体   繁体   中英

JList selection to String and be able to save in a text file

I am Creating a program for my class that is a Pizza ordering Form. I have the code set so that whatever selection is chosen it is placed into a TextField called Getmetheorder. I would like put all the selections that were picked into a text file that would be the receipt of the order.

This is how I set up the list and this is working with out any issue.

Object selected[] = toplist.getSelectedValues();
        String tops = "";
        // Use a for loop to obtain the names of the selected items
        for (int k = 0;k < selected.length ; k++ )
        {
            tops += selected[k] + ",";
        }
        Getmetheorder.setText( sizepicked + tops );

String[] selectedItems = new String[selected.length];

for(int i=0; i<selected.length;i++){
selectedItems[i] = selected[i].toString();

I would like to make it so that when the user selects Pepperoni, peppers and mushrooms for example, insert that into this text file.

   try {
BufferedWriter out = new BufferedWriter(new FileWriter("YourPizzaOrder.txt"));
out.write("Thank you for using the Online Pizza Ordering Program.");
out.newLine();
out.write("Your order was created on"+" "+today);
out.newLine();
out.write("*------------------------------------------------------*");
out.newLine();

out.write("a " + sizepicked + " With "+ //This is where i want the items from the Jlist to appear );
out.close();
}
catch (IOException e)
{
  System.out.println("Exception ");
}

The sizepicked Variable is from a button group selection of small, medium, and large. That is working and outputting to the text file as planned. I am just a bit confused on how I would get the list selection to appear.

this is for saving the selected items to a text file:

  List<Object> myList= list.getSelectedValuesList();
    try {
        BufferedWriter buffer = new BufferedWriter(new FileWriter(new File("file.txt"),true));
        for(int i = 0 ; i<myList.size();i++){
            buffer.write(myList.get(i).toString());
            buffer.flush();
        }
        buffer.close();

    } catch (IOException ex) {
        //....
    }

and for showing all the selected values you can use JTable or JList , I would prefer JList it's easy for using :

JList list2 = new JList(myList.toArray());

You could do something like...

StringBuilder sb = new StringBuilder(64);
for (String value : selectedItems) {
    if (sb.length() > 0) {
        sb.append(", ");
    }
    sb.append(value);
}

out.write("a " + sizepicked + " With "+ sb.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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