开发者

JTextField DocumentListener/DocumentEvent

开发者 https://www.devze.com 2022-12-20 17:59 出处:网络
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

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


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);    
            }
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号