Search code examples
javanetbeans

Unable to get documentlistener to work enable or disable a button in Java (Netbeans), what am I doing wrong?


I'm trying to enable or disable a button based on whether a text area is empty and for further context, I'm doing this in Netbeans. The button disabled by default.

Based on my research so far, what I need to detect the change in the text area is a document listener... No matter how I add the code that I have managed to figure out an plagiarize, it either has errors in it or does nothing... messagearea is the name of my textarea and sendb is the button. This is the best I have so far:

public NewJFrame (DocumentListener Frame){
    messagearea.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
            if (messagearea.getText().equals("")){
                sendb.setEnabled(false);
                System.out.println("false");
            } else
            {
                sendb.setEnabled(true);
                System.out.println("true");
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
            if (messagearea.getText().equals("")){
                sendb.setEnabled(false);
                System.out.println("false");
            } else
            {
                sendb.setEnabled(true);
                System.out.println("true");
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
            if (messagearea.getText().equals("")){
                sendb.setEnabled(false);
                System.out.println("false");
            } else
            {
                sendb.setEnabled(true);
                System.out.println("true");
            }
        }
    });
}

I've put this after the variable declaration. It doesn't even print any output, so I know I've made a mistake in making the listener actually "listen", lol Any help would be appreciated.


Solution

  • I solved this problem.

    In the Design tab of the main class with the textarea in it I right clicked on textarea, selected properties, went to the code tab, clicked the ellipses on the Post-Listeners Code category and pasted the above code in the provided field. The button now behaves as I wanted.