Why doesn't DocumentFilter give the expected result?

I believe that this should be a simple error in the code or a misunderstanding on my part, but I cannot get DocumentFilterto detect events insertString. Below is a simple filter for uppercase letters, but this is not as important as the fact that the method is insertString(..)never called!

Why is the method insertString(..) DocumentFilternot called?

The filter is applied to the JTextFieldtop. Each time it is called insertString(..), it must add information JTextAreato CENTER. There is currently no action in the text box that adds text to the text area.

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.*;

public class FilterUpperCaseLetters {

    private JComponent ui = null;
    private final JTextField textField = new JTextField(25);
    private final JTextArea textArea = new JTextArea(5, 20);

    FilterUpperCaseLetters() {
        initUI();
    }

    public void initUI() {
        // The document filter that seems to do nothing.
        DocumentFilter capsFilter = new DocumentFilter() {
            @Override
            public void insertString(
                    DocumentFilter.FilterBypass fb,
                    int offset,
                    String string,
                    AttributeSet attr) throws BadLocationException {
                textArea.append("insertString! " + string + "\n");
                if (!string.toUpperCase().equals(string)) {
                    textArea.append("Insert!\n");
                    super.insertString(fb, offset, string, attr);
                } else {
                    textArea.append("DON'T insert!\n");
                }
            }
        };
        AbstractDocument abstractDocument
                = (AbstractDocument) textField.getDocument();
        abstractDocument.setDocumentFilter(capsFilter);

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ui.add(textField, BorderLayout.PAGE_START);
        ui.add(new JScrollPane(textArea), BorderLayout.CENTER);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                FilterUpperCaseLetters o = new FilterUpperCaseLetters();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
+4
source share
1 answer

replaceSelection(...) , , replace(...) AbstractDocument replace(...) DocumentFilter.

insertString(...) DocumentFilter Document.insertString(...) Document.

, , , .

, , :

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class UpperCaseFilter extends DocumentFilter
{
    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
        throws BadLocationException
    {
        replace(fb, offs, 0, str, a);
    }

    public void replace(FilterBypass fb, final int offs, final int length, final String str, final AttributeSet a)
        throws BadLocationException
    {
        if (str != null)
        {
            String converted = convertString(str);
            super.replace(fb, offs, length, converted, a);
        }
    }

    private String convertString(String str)
    {
        char[] upper = str.toCharArray();

        for (int i = 0; i < upper.length; i++)
        {
            upper[i] = Character.toUpperCase(upper[i]);
        }

        return new String( upper );
    }

    private static void createAndShowGUI()
    {
        JTextField textField = new JTextField(10);
        AbstractDocument doc = (AbstractDocument) textField.getDocument();
        doc.setDocumentFilter( new UpperCaseFilter() );

        JFrame frame = new JFrame("Upper Case Filter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new java.awt.GridBagLayout() );
        frame.add( textField );
        frame.setSize(220, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }

}
+7

Source: https://habr.com/ru/post/1598473/


All Articles