0

我的问题是如何暂时禁用 JOptionPane 输入对话框上的确定按钮,直到按下一个键?

4

1 回答 1

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);
于 2012-11-05T09:24:30.763 回答