如果JTextField文档为空,如何指定JButton状态

时间:2016-03-26 08:46:39

标签: java swing actionlistener documentlistener

所以我今天刚开始阅读DocumentListeners和其他一些动作听众,但是当任何文本字段都是JButton时,我无法恢复setEnabled(false)状态空。这是否与插入符号位置有关,或者当任何文本字段为空时,是否有正确的方法将其还原为原始状态setEnabled(false)

这是我到目前为止所写的内容。

public class home extends javax.swing.JPanel {
    public home() {
        JPasswordField currentPasswordJPasswordField;
        JPasswordField newPasswordJPasswordField;
        JPasswordField reTypeNewPasswordJPasswordField;

        currentPasswordJPasswordField.getDocument().addDocumentListener(new textFieldListener(saveNewPasswordButton));
        newPasswordJPasswordField.getDocument().addDocumentListener(new textFieldListener(saveNewPasswordButton));
        reTypeNewPasswordJPasswordField.getDocument().addDocumentListener(new textFieldListener(saveNewPasswordButton));
    }

    public static class textFieldListener implements DocumentListener {
        JButton btn;

        public textFieldListener(JButton button) {
            btn = button;
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            btn.setEnabled(true);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            btn.setEnabled(true);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            btn.setEnabled(true);
        }
    }
}

当我在文本字段中输入内容时,它会按预期启用保存按钮。 但是当我按退格键清除所有文字时,保存按钮不会恢复为 setEnabled(false)

我很感激任何回应。我刚开始学习这个。我还想知道是否可以将动作侦听器放在单独的.java文件中。如果是这样,我如何将监听器应用于我的主类。

感谢。

2 个答案:

答案 0 :(得分:4)

您的基本方法是正确的,使用DocumentListener,但您似乎无法随时检查Document内容的长度

这是一个非常简单的例子,但是直到所有三个字段中都包含某些内容,按钮才会启用。

你可以通过检查前两个字段是否匹配来扩展这个想法,但我会把它留给你

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPasswordField currentPasswordJPasswordField;
        private JPasswordField newPasswordJPasswordField;
        private JPasswordField reTypeNewPasswordJPasswordField;     

        private List<JTextComponent> requiredFields = new ArrayList<>(25);

        private JButton okay;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2, 2, 2, 2);
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            currentPasswordJPasswordField = makePasswordField();
            newPasswordJPasswordField = makePasswordField();
            reTypeNewPasswordJPasswordField = makePasswordField();

            add(currentPasswordJPasswordField, gbc);
            add(newPasswordJPasswordField, gbc);
            add(reTypeNewPasswordJPasswordField, gbc);

            okay = new JButton("Ok");
            add(okay);

            updateState();
        }

        protected JPasswordField makePasswordField() {
            JPasswordField field = new JPasswordField(20);
            field.getDocument().addDocumentListener(new DocumentHandler());
            requiredFields.add(field);
            return field;
        }

        protected void updateState() {
            boolean enabled = true;
            for (JTextComponent field : requiredFields) {
                if (field.getDocument().getLength() == 0) {
                    enabled = false;
                    break;
                }
            }
            okay.setEnabled(enabled);
        }

        public class DocumentHandler implements DocumentListener {

            @Override
            public void insertUpdate(DocumentEvent e) {
                updateState();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateState();
            }

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

        }

    }

}

答案 1 :(得分:1)

您可以为每个文本字段添加KeyListener,并从匿名内部类中更新按钮。

currentPasswordJPasswordField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        super.keyReleased(e);
        if(currentPasswordJPasswordField.getText().length() > 0 && 
                newPasswordJPasswordField.getText().length() > 0 && 
                reTypeNewPasswordJPasswordField.getText().length() > 0) {
            btn.setEnabeld(true);
        } else {
            btn.setEnabled(false);
        }
    }
});

newPasswordJPasswordField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        super.keyReleased(e);
        if(currentPasswordJPasswordField.getText().length() > 0 && 
                newPasswordJPasswordField.getText().length() > 0 && 
                reTypeNewPasswordJPasswordField.getText().length() > 0) {
            btn.setEnabeld(true);
        } else {
            btn.setEnabled(false);
        }
    }
});

reTypeNewPasswordJPasswordField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        super.keyReleased(e);
        if(currentPasswordJPasswordField.getText().length() > 0 && 
                newPasswordJPasswordField.getText().length() > 0 && 
                reTypeNewPasswordJPasswordField.getText().length() > 0) {
            btn.setEnabeld(true);
        } else {
            btn.setEnabled(false);
        }
    }
});