Kalle Richter
Kalle Richter

Reputation: 8728

How to manipulate text pasted into a JTextField, but not typed input?

My application offers the possibility to copy text from a JTextArea to a JTextField (used as editor component of a JComboBox, but I assume that doesn't matter) and I'd like to provide to remove leading and trailing whitespace if a boolean condition is true (e.g. a check box is checked). Entering leading and trailing whitespace into the JTextField should still be possible, only the pasted text should be manipulated as described.

I added a DocumentFilter, but it responds to both typed changes and pasted changes and I don't find any condition in its method arguments which allow to distinguish typed from pasted insertions. A KeyListener doesn't respond to pasted changes.

Upvotes: 1

Views: 819

Answers (2)

user3437460
user3437460

Reputation: 17454

I don't find any condition in its method arguments which allow to distinguish typed from pasted insertions. A KeyListener doesn't respond to pasted changes.

Listener does not provide a direct means to determine whether the input comes from a paste-action. But I have a simple work around solution which may work.

  1. Use a DocumentListener to detect for text changes in the JTextField. If changes were detected, proceed to next step.

  2. Grab the String text from the Clipboard object.

  3. Compare text within the JTextField and the text from the Clipboard. If the Strings are the same, we assume pasting has occurred.


In case the user paste some text in-between existing text in the textfield, you can get the caret position and compare the String from the caret position onwards.


Update:

To read from Clipboard:

import java.awt.Toolkit;
import java.awt.datatransfer.*;

Clipboard cb=Toolkit.getDefaultToolkit().getSystemClipboard();
System.out.println(cb.getData(DataFlavor.stringFlavor));

Upvotes: 4

camickr
camickr

Reputation: 324108

I added a DocumentFilter, but it responds to both typed changes and pasted changes and I don't find any condition in its method arguments which allow to distinguish typed from pasted insertions

I have never tried it but maybe you can use the EventQueue class. Specifically you might be able to use the getCurrentEvent() method.

I would guess that if the event type is keyTyped then it was generated by typing into the text field.

Other events would be generated if the paste was done using CTRL_V from the keyboard or if you click on a menu item that does the paste.

So I would guess you just need to check if the event is not a "KeyTyped" event and invoke your custom paste logic.

Upvotes: 0

Related Questions