java - 如何临时禁用 JOptionPane 输入对话框上的“确定”按钮?

标签 java swing joptionpane

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

最佳答案

这是一个例子:

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

关于java - 如何临时禁用 JOptionPane 输入对话框上的“确定”按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13228788/

相关文章:

java - java中如何使用参数和实参?

java - Java Collections 在使用 Collections.addAll() 时什么时候抛出 NullPointerException

java - 防止 Java 在更新时重新绘制 JPanel 的内容

java - 在 JOptionPane 中显示 JDateChooser

java - 返回错误 int 值的变量

java - 如何在异构系统中实现SSO(Java和Web应用程序)

java - Postman 的发布请求问题

java - 在 JFrame 中绘制 Graphics2D

用于从本地系统搜索所有 .doc 和 .docx 文件的 java 代码

java - JFrame 中显示的 JOptionPane 文本