Multiple Choice from JOptionPane

I have an arraylist with objects and running Gui. I am looking for a way to pop-up a window or a frame, or something like what displays objects in arraylist. The user should now be able to select one or more items that are then returned.

I already have an option, but I can just select one object

Object[] possibilities = lr.declarationList.toArray(); String s = (String)JOptionPane.showInputDialog( gui.getFrame(), "Choose Target Nodes", "Customized Dialog", JOptionPane.PLAIN_MESSAGE, null, possibilities, null); 

perhaps a popup list will help.

+4
source share
2 answers

Try using JOptionPane.showMessageDialog(...) with the argument of the JList component whose elements are obtained from your list, for example:

 JList list = new JList(new String[] {"foo", "bar", "gah"}); JOptionPane.showMessageDialog( null, list, "Multi-Select Example", JOptionPane.PLAIN_MESSAGE); System.out.println(Arrays.toString(list.getSelectedIndices())); 

Please note: if you need more layout elements in the message object itself, you can pack them all in JPanel and use this component as an argument to the message.

+9
source

Here is the version using JCheckBox :

 import javafx.util.Pair; public static <T> List<T> select(Component parent, String message, List<T> variants) { List<Pair<JCheckBox, T>> boxes = variants .stream() .map(variant -> new Pair<>(new JCheckBox(String.valueOf(variant)), variant)) .collect(Collectors.toList()); JPanel panel = new JPanel(new GridBagLayout()); boxes.forEach(p -> panel.add(p.getKey(), new GridBagConstraints( 0, boxes.indexOf(p), 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0 ) )); JOptionPane.showMessageDialog(parent, panel, message, JOptionPane.PLAIN_MESSAGE); return boxes.stream() .filter(p -> p.getKey().isSelected()) .map(Pair::getValue) .collect(Collectors.toList()); } 
0
source

Source: https://habr.com/ru/post/1391516/


All Articles