How to get JTextField name in which is Document placed?

狂风中的少年 提交于 2019-12-29 08:04:28

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/5774732/how-to-get-jtextfield-name-in-which-is-document-placed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!