我正在为我的课程创建一个比萨订购表格的程序。我有代码集,所以无论选择什么选择,它都被放入一个名为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变量来自小,中,大的按钮组选择。这是工作并按计划输出到文本文件。我对如何让列表选择出现感到困惑。
答案 0 :(得分: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) {
//....
}
为了显示您可以使用JTable
或JList
的所有选定值,我希望JList
使用起来很简单:
JList list2 = new JList(myList.toArray());
答案 1 :(得分: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());