Search code examples
javaswingawtjtextfield

Can I make UndoManager consider DocumentFilter?


Run this example:

public class UndoRedoSSCCE extends JFrame {

    public UndoRedoSSCCE() {
        super("A");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLayout(new FlowLayout());

        JComboBox<String> comboBox = new JComboBox<>(new String[] { "letters & digits", "only digits" });
        JTextField textField = new JTextField(15);
        PlainDocument doc = new PlainDocument();
        textField.setDocument(doc);
        installUndoRedo(textField);

        comboBox.addActionListener(e -> {
            textField.setText("");
            if (comboBox.getSelectedIndex() == 0)
                doc.setDocumentFilter(new LettersAndDigitsFilter());
            else
                doc.setDocumentFilter(new OnlyDigitsFilter());
        });
        doc.setDocumentFilter(new LettersAndDigitsFilter());

        add(comboBox);
        add(textField);

        pack();
        setLocationByPlatform(true);
    }

    private static class LettersAndDigitsFilter extends DocumentFilter {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            string.chars().filter(c -> Character.isDigit(c) || Character.isLetter(c))
                    .forEach(value -> sb.append((char) value));

            super.insertString(fb, offset, sb.toString(), attr);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            text.chars().filter(c -> Character.isDigit(c) || Character.isLetter(c))
                    .forEach(value -> sb.append((char) value));

            super.replace(fb, offset, length, sb.toString(), attrs);
        }
    }

    private static class OnlyDigitsFilter extends DocumentFilter {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            string.chars().filter(Character::isDigit).forEach(value -> sb.append((char) value));

            super.insertString(fb, offset, sb.toString(), attr);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            text.chars().filter(Character::isDigit).forEach(value -> sb.append((char) value));

            super.replace(fb, offset, length, sb.toString(), attrs);
        }
    }

    public static void installUndoRedo(JTextComponent textComponent) {
        UndoManager undoManager = new UndoManager();
        textComponent.getDocument().addUndoableEditListener(undoManager);
        InputMap im = textComponent.getInputMap(JComponent.WHEN_FOCUSED);
        ActionMap am = textComponent.getActionMap();

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Undo");
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Redo");

        am.put("Undo", new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
            }
        });
        am.put("Redo", new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (undoManager.canRedo()) {
                    undoManager.redo();
                }
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new UndoRedoSSCCE().setVisible(true);
        });
    }
}

If i enter a text with letters and digits and select in the combo box "Only letters", when I press control Z, these letters and digits will appear in the text field. With other words, UndoManager ignores the document filter.

See this gif:

enter image description here

When I change combo box selection, the text becomes blank. Then I press CTRL+ Z and the text that contains letters appears while the OnlyDigits filter is on.

I know that I can undoManager.discardAllEdits, but is it possible to make it work? I mean to apply the filter when redo/undo is attempted?

I also tried to @Override some methods from PlainDocument but they are not called either in order to override something meaningful.


Solution

  • Undo/Redo should restore the state of the component not alter the state.

    I would suggest that when you change the filter you should:

    1. Save the current text,
    2. clear the text in the text field
    3. invoke discardAllEdits() on the UndoManager.
    4. iterate through the old text one character at a time and insert the character back into the Document. This will allow the text to be filtered while rebuilding the undo/redo as if the text was entered using the current filter.