我想在 JOptionPane 中显示 for 循环的输出

I want to show output from for loop in JOptionPane

我有一个 ArrayList,我想遍历 ArrayList 并将数组列表中的项目打印到 JOptionPane.showInput 对话框。但是我如何在 JOptionPane 中使用循环结构?下面的代码显示了多个 JOptionPane windows 并且很明显它会因为它在一个循环中。谁能修改它以仅显示一个 JOptionPane window 并在一个 window.

中输出所有消息
public void getItemList(){
          for (int i=0; i<this.cartItems.size(); i++){
           JOptionPane.showInputDialog((i+1) + "." +
                    this.cartItems.get(i).getName(););
        }
            
    } 

您可以将 cartItems 的所有元素附加到 StringBuilder 中,并在循环终止后仅显示一次带有 StringBuilderJOptionPane

import java.util.List;

import javax.swing.JOptionPane;

public class Main {
    List<String> cartItems = List.of("Tomato", "Potato", "Onion", "Cabbage");

    public static void main(String[] args) {
        // Test
        new Main().getItemList();
    }

    public void getItemList() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < this.cartItems.size(); i++) {
            sb.append((i + 1) + "." + this.cartItems.get(i)).append(System.lineSeparator());
        }
        JOptionPane.showInputDialog(sb);
    }
}

您需要定义一个字符串变量并将 ArrayList 的每个值放入其中,然后用“\n”(换行符)分隔每个值,并在循环结束后显示输入对话框:

public static void getItemList(){
    String value = "";
    for (int i=0; i<this.cartItems.size(); i++){
        value += (i+1) + "." + this.cartItems.get(i).getName() + "\n";
    }  
    JOptionPane.showInputDialog(value);
}

方法 showInputDialog() 中的 message 参数可以是 java.lang.Object 的任何子类,包括 javax.swing.JList.

// Assuming 'cartItems' is instance of 'java.util.List'
JList<Object> list = new JList<>(cartItems.toArray());
JOptionPane.showInputDialog(list);

参考How to Make Dialogs