I added a documentListener to a jTextArea, which should set a button disabled whenever the textArea is empty.
This works just at the starting point when the textArea is empty, but when I type something and then delete all the text until textArea.getText() == ""
, the button still doesn't turn disabled again.
This is what I wrote:
textArea.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
if (textArea.getText() == null) {
disableButton();
} else {
enableButton();
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (textArea.getText() == null) {
disableButton();
} else {
enableButton();
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (textArea.getText() == null) {
disableButton();
} else {
enableButton();
}
}
public void enableButton() {
clearModelMenuItem.setEnabled(true);
discardModel.setEnabled(true);
increaseFontSize.setEnabled(true);
decreaseFontSize.setEnabled(true);
incMenuItem.setEnabled(true);
decMenuItem.setEnabled(true);
}
What is the problem here? Thanks for helping!
It's because you're not actually checking whether the text is empty; you're checking whether it's null
. There's a difference between a String
that's empty and a String
that's null
.
You need to be checking
if ("".equals(textArea.getText())) ...
if you want to check whether it's empty.
(You might also want to check for null
.)