Search code examples
javaswingjtextfieldjcomponent

Catch paste action by middle mouse button


I'm working on a linux machine and different from windows there are two clipboards, the STRG-C and STRG-V clipboard and the highlight text and paste by middle mouse button clipboard.

Now i try to catch the paste action, because i want to validate the clipboard and prevent the textfield from illegal input.

I successfully catched the standard paste by STRG-V with:

Action action = textField.getActionMap().get("paste-from-clipboard");
textField.getActionMap().put("paste-from-clipboard", new ProxyAction(action, "paste-from-clipboard"));

and the implementation of ProxyAction class:

    public class ProxyAction extends TextAction
    {
        private Action action;

        public ProxyAction1(Action action, String actionName)
        {
            super(actionName);
            this.action = action;
       }

       @Override
       public void actionPerformed(ActionEvent e)
       {
           action.actionPerformed(e);
       }
   }

My question is, how can i catch the linux specific middle mouse button paste? The code above doesn't get it and the action "paste" from jTextfield doesn't solve the problem either.


Solution

  • i want to validate the clipboard and prevent the textfield from illegal input.

    Instead of trying to catch the paste keys, you can use a DocumentFilter. The DocumentFilter is invoked before any text is inserted into a Document.

    This filter is invoked whether text is typed into the text field or pasted into the text field.

    Check out the section from the Swing tutorial on How to Implement a DocumentFilter for more information.