如何临时禁用JOptionPane输入对话框上的OK按钮?

时间:2012-11-05 08:58:04

标签: java swing joptionpane

我的问题是如何临时禁用JOptionPane输入对话框上的OK按钮,直到按下某个键?

1 个答案:

答案 0 :(得分:1)

以下是一个例子:

JPanel pan = new JPanel(new BorderLayout());
final JTextField txt = new JTextField(10);
final JButton ok = new JButton("OK");
ok.setEnabled(false);

ok.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        String input = txt.getText();
        System.out.println("The input is: " + input);

        /* close the dialog */
        Window w = SwingUtilities.getWindowAncestor(ok);
        if(w != null) w.setVisible(false);
    }
});

txt.getDocument().addDocumentListener(new DocumentListener()
{
    @Override
    public void removeUpdate(DocumentEvent e)
    {
        if(e.getDocument().getLength() == 0) ok.setEnabled(false);
    }

    @Override
    public void insertUpdate(DocumentEvent e)
    {
        if(e.getDocument().getLength() > 0) ok.setEnabled(true);
    }

    @Override
    public void changedUpdate(DocumentEvent e){}
});

pan.add(txt, BorderLayout.NORTH);
JOptionPane.showOptionDialog(null, pan, "The Title", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, new JButton[]{ok}, ok);