Search code examples
javaeclipseswingjtextareadocumentlistener

How to add an Document Listener to a JTextArea inside of a JScrollPane?


I'm trying to add an Document Listener to a JTextArea, so that when a user presses enter it will read in the last line / the characters since the new line.

I tried the following code, but Eclipse doesn't like display.getDocument().addDocumentListener(new AL());. It says

No enclosing instance of type ScrollingTextArea is accessible. Must qualify the allocation with an enclosing instance of type ScrollingTextArea (e.g. x.new A() where x is an instance of ScrollingTextArea).

How can I add an Action Listener to a JTextArea?

Code:

package guis;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class ScrollingTextArea {

    public static void main ( String[] args )
    {
        JPanel middlePanel = new JPanel ();
        middlePanel.setBorder(new TitledBorder(new EtchedBorder (), "Display Area" ) );

        // create the middle panel components

        JTextArea display = new JTextArea(16,58 );
        JScrollPane scroll = new JScrollPane(display);

        display.getDocument().addDocumentListener(new AL());
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        //Add Textarea in to middle panel
        middlePanel.add(scroll);

        JFrame frame = new JFrame();
        frame.add( middlePanel );
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public class AL implements DocumentListener {


        @Override
        public void insertUpdate(DocumentEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            // TODO Auto-generated method stub

        }
    }
}

Solution

  • The nested class, AL, needs to be static. Unless you need to export the class for some reason, it should probably be private.

    private static class AL implements DocumentListener {…}