I have a textField in my application which will be initiated programmatically (textField.setText() ) when user clicked in an item in JList. later user will change this value manually. I get stuck with using document-listener to detect changes in this text field. When changes happens programmatically it must do nothing but if manually happens, it should change the background to red.
How to detect whether textField has been filled out manually or by textField.setText()?
txtMode.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
if (!mode.equals(e.getDocument()))
txtMode.setBackground(Color.red);
}
public void removeUpdate(DocumentEvent e) {
if (mode.equals(e.getDocument()))
txtMode.setBackground(Color.white);
}
public void changedUpdate(DocumentEvent e) {
//To change body of implemented methods
}
});
there are two ways
DocumentListener
before setText("...")
add DocumentListener
back if donecode
public void attachDocumentListener(JComponent compo){
compo.addDocumentListener(someDocumentListener);
}
//similair void for remove....
boolean
value for disabling "if needed", but you have to change contens of your DocumentListener
for example
txtMode.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
if (!mode.equals(e.getDocument()))
if (!updateFromModel){
txtMode.setBackground(Color.red);
}
}
public void removeUpdate(DocumentEvent e) {
if (mode.equals(e.getDocument()))
if (!updateFromModel){
txtMode.setBackground(Color.white);
}
}
public void changedUpdate(DocumentEvent e) {
//To change body of implemented methods
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With