Reputation: 128
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(););
}
}
Upvotes: 2
Views: 1299
Reputation: 20914
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
Upvotes: 3
Reputation: 3027
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);
}
Upvotes: 2
Reputation: 79105
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);
}
}
Upvotes: 3