I wil select multiple values from an JOptionpane in Java. What is the solution to get these multiple values out of this pane. When I tried always got only one value back while i selected two or more selections.
String bigList[] = new String[bankReferentie.aantalKlanten()];
for (int i = 0; i < bigList.length; i++) {
bigList[i] = bankReferentie.getKlanten(i).toString();
}
JOptionPane.showMessageDialog(null, new JList(bigList), "Rekening", JOptionPane.PLAIN_MESSAGE);
The trick here is to create a JList
before showing the option pane, then query it after the option pane is shown.
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.*;
class MultiSelectListInOptionPane {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
String[] fruit = {"Apple", "Banana", "Grapefruit", "Orange"};
JList<String> list = new JList<String>(fruit);
gui.add(new JScrollPane(list));
JOptionPane.showMessageDialog(
null,
gui,
"Rekening",
JOptionPane.QUESTION_MESSAGE);
List items = (List)list.getSelectedValuesList();
for (Object item : items) {
System.out.println("Selected: " + item);
}
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
run:
Selected: Banana
Selected: Orange
BUILD SUCCESSFUL (total time: 7 seconds)