views:

313

answers:

1

Hello all, 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

+3  A: 

Hi,

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);    
            }
        }
    }
}
Klarth
that works exactly like what i was wanting, thank you for that :)
Lonnie Ribordy
How would i change the PREFIX seeing as how the current path will change.
Lonnie Ribordy
You need to change it so that the custom document keeps track of what is in the prompt and its length. I would also add a method in the custom document to change the prompt and to get the contents after the prompt. The method setting the prompt needs to use the methods in super to change the prompt, since they would have been overridden by the custom document. I've already written up an example at http://www.box.net/shared/jjbzrz8fqe
Klarth