1

我正在为我的班级创建一个比萨订购表的程序。我设置了代码,因此无论选择什么选择,它都会被放入一个名为 Getmetheorder 的 TextField 中。我想将所有选择的选项放入一个文本文件中,该文件将作为订单的收据。

这就是我设置列表的方式,这没有任何问题。

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();

我想这样当用户选择意大利辣香肠、辣椒和蘑菇时,将其插入到这个文本文件中。

   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 ");
}

sizepicked 变量来自小、中和大的按钮组选择。这是按计划工作并输出到文本文件。我对如何显示列表选择有点困惑。

4

2 回答 2

0

这是为了将所选项目保存到文本文件中:

  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) {
        //....
    }

为了显示您可以使用的所有选定值JTableor JList,我希望JList它易于使用:

JList list2 = new JList(myList.toArray());
于 2013-05-05T22:08:59.543 回答
0

你可以做类似...

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());
于 2013-05-05T22:29:50.453 回答