【问题标题】:Multiple choices from a JOptionPane来自 JOptionPane 的多个选择
【发布时间】:2012-02-12 13:13:13
【问题描述】:

我有一个包含对象的数组列表和一个正在运行的 Gui。我正在寻找一种方法来弹出一个小框架或框或类似的东西来显示来自arraylist的对象。用户现在应该能够选择一个或多个然后返回的项目。

我已经有了选项窗格,但我只能选择一个对象

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

也许弹出列表会有所帮助。

【问题讨论】:

  • 您是否尝试过运行Java教程中How to Use Dialogs中的相应示例?将SSCCE 放在这里。顺便说一句,您是否尝试将可能性设置为一个简单的数组({“ham”、“spam”、“yam”})。

标签: java swing user-interface joptionpane


【解决方案1】:

尝试将 JOptionPane.showMessageDialog(...) 与 JList 组件参数一起使用,其元素来自您的列表,例如:

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

请注意,如果您在消息对象本身中需要更多布局项,您可以将它们全部打包到 JPanel 中并将该组件用作消息参数。

【讨论】:

  • 也许 JComboBox +1 :-) {"ham", "spam", "yam"} :-)
  • 非常感谢您简单明了的回答!我已经花了两个小时试图弄清楚如何做到这一点。我对自己制作的第一个部分工作版本的复杂程度感到震惊......
【解决方案2】:

这是一个使用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());

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    相关资源
    最近更新 更多