Question

i would like to know how to use a DocumentListener/DocumentEvent in java to prevent the user from deleting a certain portion of text in a JTextField, like on the windows command prompt or unix Terminal.. they show the current working directory and you can't delete past the > or $

can anyone help me? thanks

Was it helpful?

Solution

The problem with using adding on a DocumentListener is that you can't tack back the part that was deleted or edited from within the listener, otherwise you'll get an exception saying that you are trying to modify the contents when you have the notification. The easiest way I know is to subclass a Document, override remove on the Document and set the text field to use the document, like in my example below:

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;

public class Application {

    private static final String PREFIX = "Your Input>";

    private static final int prefixLength = PREFIX.length();

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame rootFrame = new JFrame();
        JTextField textField = new JTextField(new PromptDocument(), PREFIX, 20);

        rootFrame.add(textField);
        rootFrame.pack();
        rootFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        rootFrame.setVisible(true);
    }

    private static class PromptDocument extends DefaultStyledDocument {

        private static final long serialVersionUID = 1L;

        @Override
        public void remove(int offs, int len) throws BadLocationException {
            if (offs > prefixLength - 1) {
                int buffer = offs - prefixLength;
                if (buffer < 0) {
                    len = buffer;
                }
                super.remove(offs, len);    
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top