java – JTextField,其中不可编辑但其他文本的预定义文本可以附加到它?

在经历Java swing时我遇到了这个问题.
我有一个JTextField,它有预定义的,不可编辑的文本.用户应该能够将其他文本附加到其中但不编辑预定义文本.是否有任何方法可以获得此解决方案或任何其他方法?
您只需使用DocumentFilter即可:

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestDocumentFilter {

    private static final String TEXT_NOT_TO_TOUCH = "You can't touch this!";

    private void initUI() {
        JFrame frame = new JFrame(TestDocumentFilter.class.getSimpleName());
        frame.setLayout(new FlowLayout());
        final JTextField textfield = new JTextField(50);
        textfield.setText(TEXT_NOT_TO_TOUCH);
        ((AbstractDocument) textfield.getDocument()).setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                if (offset < TEXT_NOT_TO_TOUCH.length()) {
                    return;
                }
                super.insertString(fb, offset, string, attr);
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                if (offset < TEXT_NOT_TO_TOUCH.length()) {
                    length = Math.max(0, length - TEXT_NOT_TO_TOUCH.length());
                    offset = TEXT_NOT_TO_TOUCH.length();
                }
                super.replace(fb, offset, length, text, attrs);
            }

            @Override
            public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
                if (offset < TEXT_NOT_TO_TOUCH.length()) {
                    length = Math.max(0, length + offset - TEXT_NOT_TO_TOUCH.length());
                    offset = TEXT_NOT_TO_TOUCH.length();
                }
                if (length > 0) {
                    super.remove(fb, offset, length);
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textfield);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestDocumentFilter().initUI();
            }
        });
    }

}
https://stackoverflow.com/questions/16294982/jtextfield-in-which-the-predefined-text-in-not-editable-but-other-text-can-be-ap

转载注明原文:java – JTextField,其中不可编辑但其他文本的预定义文本可以附加到它?