0

I have a question about use case of JtextPane. Indeed, I delevelop an application using an MVC architecture. My frame has a Jtextpane with keylistener to permit all user to edit text.

But as MVC architecture wants (and as i want too), I have to control characters typed before display it on the JtextPane. So, I use the Observer/Observable pattern to update my JtextPane.

But, how can I typed any charcter of my keyboard without display it automoticlly on my JtextPane. Indeed, when I press any key on my keyboard, it display it automaticly .. Like I said I want to update my JtextPane by myself.

Of course, if I do :

 mytextPane.setEnabled(false)

my keyListener can't works and so any control too...

Bigote
  • 95
  • 7

2 Answers2

2

You should use filtering capability of text components. Here is a small example:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/**
 * <code>TextPaneFilter</code>.
 */
public class TextPaneFilter {

    public static void main(String[] args) {
        // start UI in Event Dispatcher Thread (EDT)
        SwingUtilities.invokeLater(new TextPaneFilter()::startUI);
    }

    private void startUI() {
        JTextPane textPane = new JTextPane();
        textPane.setContentType("text/html");
        textPane.setText("<html>Plain <b>Bold</b> <i>Italic</i></html>");
        AbstractDocument doc = (AbstractDocument) textPane.getDocument();
        doc.setDocumentFilter(new DocFilter());
        JScrollPane scroller = new JScrollPane(textPane);
        JFrame frm = new JFrame("Text filter");
        frm.add(scroller);
        frm.setSize(500, 300);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    private static class DocFilter extends DocumentFilter {

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            boolean hasDigit = text.chars().anyMatch(i -> Character.isDigit((char) i));
            if (!hasDigit) {
                super.replace(fb, offset, length, text, attrs);
            }
        }
    }
}

For more information about filtering in text components see here.

Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
  • (1+) for being the first answer. I included my simple example to show a complete implementation of the `DocumentFilter` by implementing the `insertString(...)` method. This may or may not be an issue (depending on the exact requirement. See: https://stackoverflow.com/questions/31487465/why-does-the-documentfilter-not-give-the-intended-result/31487599#31487599 for the reason to implement both the `replace()` and `insertString()` methods. – camickr Jul 03 '19 at 14:10
  • @camickr Thanks, I know it. But the topic starter have asked about keyboard input, so I've skipped the method `insertString`. – Sergiy Medvynskyy Jul 03 '19 at 14:15
  • Thank you for your answer; Do you know how can I detect Back_Space event using Document Filter ? – Bigote Jul 05 '19 at 12:10
2

Don't use a KeyListener.

The Swing Document supports a DocumentFilter, which allows you to edit/verify the text before the text is inserted into the Document.

For example, the following code will convert each character to upper case as it is typed:

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 text, final AttributeSet a)
        throws BadLocationException
    {
        if (text != null)
        {
            super.replace(fb, offs, length, text.toUpperCase(), a);
        }
    }

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

See the section from the Swing tutorial on Implementing a DocumentFilter for more information and examples.

camickr
  • 321,443
  • 19
  • 166
  • 288