选择输入选项后关闭JOptionPane

时间:2015-03-20 01:03:12

标签: java swing

我正在使用JOptionPane,我希望它在用户选择了一个选项后自动关闭。 目前这是有效的,但我仍然需要手动单击确定按钮关闭JOptionPane。无论如何,当勾选复选框时我可以关闭它

JPanel a1 = new JPanel();
        a1.add(bubbleCheckBox);
       a1.add(quickCheckBox);
        a1.add(insertionCheckBox);
        a1.add(selectionCheckBox);
      //  a1.add(mergeCheckBox);

        arraySize=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter number of elements would like to sort (Recommend max =30)"));
        JOptionPane.showMessageDialog(null, a1, "Choose an algorithm to run", DEFAULT_OPTION);

    }

    public static void lockCheckboxes(JCheckBox a) throws IOException, InterruptedException {
        if (a == insertionCheckBox) {
            selectionCheckBox.setEnabled(false);
            quickCheckBox.setEnabled(false);
            bubbleCheckBox.setEnabled(false);
            mergeCheckBox.setEnabled(false);
       SortAnimator.setArraySize(arraySize);
       SortAnimator animator = new SortAnimator(new InsertionSorter());

1 个答案:

答案 0 :(得分:1)

这有点复杂。

首先,在您的ActionListener上添加JCheckBox ...

触发此ActionListener后,您需要找到包含JCheckBox的窗口,您需要找到JOptionPane的实例,调用setValue并通过它JOptionPane.OK_OPTION然后处理对话框

像...一样的东西。

JPanel a1 = new JPanel();

JCheckBox bubbleCheckBox = new JCheckBox("Bubbble");
JCheckBox quickCheckBox = new JCheckBox("Quick");
JCheckBox insertionCheckBox = new JCheckBox("Insert");
JCheckBox selectionCheckBox = new JCheckBox("Select");

ActionListener al = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JCheckBox cb = (JCheckBox) e.getSource();
        JOptionPane op = (JOptionPane) SwingUtilities.getAncestorOfClass(JOptionPane.class, cb);
        if (op != null) {
            op.setValue(JOptionPane.OK_OPTION);
        }
        SwingUtilities.getWindowAncestor(cb).dispose();
    }
};

bubbleCheckBox.addActionListener(al);
quickCheckBox.addActionListener(al);
insertionCheckBox.addActionListener(al);
selectionCheckBox.addActionListener(al);

a1.add(bubbleCheckBox);
a1.add(quickCheckBox);
a1.add(insertionCheckBox);
a1.add(selectionCheckBox);
//  a1.add(mergeCheckBox);

if (JOptionPane.showConfirmDialog(null, a1, "Choose an algorithm to run", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) {
    System.out.println("Yeah for me");
}

就个人而言,我会使用JComboBox并让用户选择确定取消