2

I have an ArrayList and i want to loop through the ArrayList and print the items in the arraylist to JOptionPane.showInput dialogue. But how can i use a looping structure in JOptionPane? The code below shows multiple JOptionPane windows and obiously it will because it is in a loop. Can anyone modify it to show only one JOptionPane window and output all messages in one window.

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

3 Answers3

3

You can append all the elements of cartItems into a StringBuilder and show the JOptionPane with the StringBuilder only once after the loop is terminated.

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

enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
3

The message parameter in method showInputDialog() can be any subclass of java.lang.Object, including a javax.swing.JList.

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

Refer to How to Make Dialogs

Abra
  • 19,142
  • 7
  • 29
  • 41
2

you need to define a string variable and put every values of ArrayList in it and then separate each value with "\n" (new line) and after ending of loop display the input dialog:

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);
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
  • 2
    You should use `StringBuilder` instead of `String` in case of repeated string concatenation within a loop. Check https://stackoverflow.com/q/7817951/10819573 for a discussion on this topic. – Arvind Kumar Avinash Nov 22 '20 at 10:58