Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

java - How to get JTextField name in which is Document placed?

Is there something like event.getSource for DocumentListener too? Im trying to change color of just one JTextField in which is text changing. Here is my DocumentListener:

DocumentListener posluchac = new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            warn(e);
        }
        public void removeUpdate(DocumentEvent e) {
            warn(e);
        }
        public void insertUpdate(DocumentEvent e) {
            warn(e);
        }
        public void warn(DocumentEvent e) {
            txtName.setBackground(Color.WHITE);
            txtSurname.setBackground(Color.WHITE);
            txtPersonalNumber.setBackground(Color.WHITE);
            txtDateOfBirth.setBackground(Color.WHITE);
        }
    };

If there is nothing like .getSource() for DocumentListener. How to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are correct, there is no getSource() like some other listeners but you can use Document class's putProperty() and getProperty() to achieve what you are looking for.

you can do

JTextField jTextField = new JTextField("Text 1");
jTextField.getDocument().putProperty("parent", jTextField);

and

later in DocumentListener's events, you can get the parent like this

JTextField textField = (JTextField) e.getDocument().getProperty("parent");

where e is DocumentEvent


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...