【问题标题】:I want to show output from for loop in JOptionPane我想在 JOptionPane 中显示 for 循环的输出
【发布时间】:2020-11-22 06:48:10
【问题描述】:

我有一个 ArrayList,我想遍历 ArrayList 并将 arraylist 中的项目打印到 JOptionPane.showInput 对话框。但是如何在 JOptionPane 中使用循环结构?下面的代码显示了多个 JOptionPane 窗口,显然它会因为它处于循环中。任何人都可以修改它以仅显示一个 JOptionPane 窗口并在一个窗口中输出所有消息。

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

【问题讨论】:

    标签: java swing joptionpane


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您需要定义一个字符串变量并将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);
      }
      

      【讨论】:

      【解决方案3】:

      方法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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-15
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 2017-02-02
        • 1970-01-01
        • 2015-09-12
        相关资源
        最近更新 更多