Disabling pasting in JTextField

I have a JTextField that has a KeyListener that prevents people from typing in certain characters. For instance, one of them only accepts numbers. It works fine, but if I copy and paste text to it (using Ctrl-v) the text pastes and the KeyEvent is never fired. SO I end up with some text like "Jun" in a JTextArea that only allows numbers. Is there a way to disable pasting on a JTextField

I've seldom used KeyListener, wherever I can, I use the component's processkeybind. The following snippet of code will trap CTRL-V before the component received it:
   JTextField myTextField = new JTextField() {
      public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
         if (ks == KeyStroke.getKeyStroke(KeyEvent.KeyEvent.VK_V,2)) return true;
         return super.processKeyBinding(ks,e,condition,pressed);
   };;o)
V.V.

Similar Messages

  • Disable pasting

    How to disable pasting from clipboard in JTextField (and in other swing text components) by pressing Ctrl-V?

    Remove the key binding. See [How to Use Key Bindings|http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html].
    db

  • Disable Paste in Text Components

    I have search everywhere I can think of for an answer to
    this. I would like to find a way to disable pasting text into a
    text component (e.g. TextInput). Could someone assist or point me
    to a site that has information on how to disable pasting (i.e. copy
    / paste) either by right-click pasting, control-v, etc.?
    Thanks.

    You could add an event listener for a TextEvent, which will
    ONLY contain a field with the text being "added". If it's being
    typed, it'll have to be length==1. If it's being pasted it'll
    probably be > 1, so perhaps you could negate the change using an
    event handler like this. Of course, this would also disable a paste
    of a single character, but people don't usually paste one character
    anyway.
    If you're able to provide this, knowing why you need to
    disable paste might help us suggest alternative solutions or
    workarounds.

  • Disable past dates in Date Navigator

    Hi All,
    Can any one let me know how to disable past dates in a Date Navigator UI element in Web Dynpro  for ABAP?
    For example,today's date is 21-May-2010,when i open my application, i want all the dates from 1 May to 20th May to be disabled.The user should not be able to select them.
    Any help would be greatly appreciated,
    Thanks,
    Salma

    Check out the Thread [Webdynpro ABAP date navigator dynamic start up date   |Webdynpro ABAP date navigator dynamic start up date;.
    After implementing this suggestion, you are now having the Error "INVALID DATE". Sort out this error with [SAP note 1370457 WDA: DateNavigator returns incorrect values|https://service.sap.com/sap/support/notes/1370457].
    Check out the thread [datenavigator exception |datenavigator exception ?; having same issue with date navigator.
    Hope it helps you.

  • Disable paste (ctrl+v) function

    Hello,
    I would like to know if is possible to disable in sapgui the paste function (ctrl+v).
    Thanks in advance,
    José Luis.

    you can disable this copy and paste action innumber of ways
    add a listener to the textfield and consume those event so that it wont propagate to the ui keybindings.
    set the action to be null for those keystrokes.
    InputMap map = JTextField.getInputMap(WHEN_FOCUSSED);
    map.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.VK_CONTROL), null);
    or
    map.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.VK_CONTROL), "none");
    Same for CTRL+C, for defeated the copy action.
    Thanks,
    Jana

  • Cut,copy,paste in jtextfield

    Hi,
    I gotta JTextField. Now I want to get a popup menu when i right-click it to ask me if i wanna cut, copy or paste using the default os clipboard.
    can anyone suggest me any helpful url ?

    Clipboard operations such as copy, cut and paste are very easy to perform on a JTextField. Just use the JTextField's void cut(), copy() and paste() methods! That's all there is to it.
    In this demo I wrote, I've shown how to use these methods, and how to create a JPopupMenu menu that appears when the user right-clicks on the JTextField, showing the three clipboard functions.
    Enjoy!
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ClipboardDemo extends JFrame implements ActionListener {
         JPanel mainPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
         JLabel descrLabel = new JLabel("Clipboard Demo by Ben James");
         JTextField theTextField = new JTextField(20);
         final JPopupMenu clipboardMenu = new JPopupMenu();
         JMenuItem cutMenuItem = new JMenuItem("Cut");
         JMenuItem copyMenuItem = new JMenuItem("Copy");
         JMenuItem pasteMenuItem = new JMenuItem("Paste");
         public ClipboardDemo() {
              super("Clipboard Demo");
              theTextField.setText("Highlight some text and right-click!");
              cutMenuItem.addActionListener(this);
              copyMenuItem.addActionListener(this);
              pasteMenuItem.addActionListener(this);
              clipboardMenu.add(cutMenuItem);
              clipboardMenu.add(copyMenuItem);
              clipboardMenu.add(pasteMenuItem);
              theTextField.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                             clipboardMenu.show(evt.getComponent(), evt.getX(), evt.getY());
              mainPane.add(descrLabel);
              mainPane.add(theTextField);
              mainPane.setPreferredSize(new Dimension(250,75));
              WindowListener wl = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              setContentPane(mainPane);
              addWindowListener(wl);
              pack();
              setResizable(false);
              setVisible(true);
         public void actionPerformed(ActionEvent evt) {
              Object source = evt.getSource();
              if (source == cutMenuItem) {
                   theTextField.cut();
              if (source == copyMenuItem) {
                   theTextField.copy();
              if (source == pasteMenuItem) {
                   theTextField.paste();
         public static void main(String[] args) {
              ClipboardDemo cd = new ClipboardDemo();
    }

  • Copy/Paste in JTextField using JMenuItems/Keystrokes

    I'm having trouble getting this to work, could someone please point me in the right direction? I've made this as much SCCE as possible so it probably won't compile but you can see what I'm trying to do... Neither the menu items nor the keypresses seem to copy or paste.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Main extends JFrame implements ActionListener, KeyListener
        private JMenuBar menuBar;
        private JMenu mEdit;
        private JMenuItem copyItem, pasteItem;
        private JTextField output;
        private static final int WIN_WIDTH=300, WIN_HEIGHT=300;
        public Main()
            super("Main");
            this.setSize(WIN_WIDTH,WIN_HEIGHT);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLayout(new BorderLayout());
            this.setJMenuBar(createMenu());
            this.setResizable(false);
            this.setIconImage(new ImageIcon("icon.png").getImage());
            this.addKeyListener(this);
            this.setFocusable(true);
            this.add(createTxtField());
        public Component createTxtField()
            output = new JTextField();
            output.setBounds(5, 5, 240, 30);
            // output.setEditable(false);
            output.setVisible(true);
            output.setEnabled(true);
            output.setText("0.");
            output.setBackground(Color.WHITE);
            output.setHorizontalAlignment(JTextField.RIGHT);
            return output;
        public JMenuBar createMenu()
            // Create the menu bar.
            menuBar = new JMenuBar();
            // Build the first menu.
            mEdit = new JMenu("Edit");
            menuBar.add(mEdit);
            // Build items for first menu.
            copyItem = new JMenuItem("Copy", KeyEvent.VK_C);
            copyItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_C, ActionEvent.CTRL_MASK));
            copyItem.addActionListener(this);
            copyItem.addKeyListener(this);
            mEdit.add(copyItem);
            pasteItem = new JMenuItem("Paste", KeyEvent.VK_V);
            pasteItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_V, ActionEvent.CTRL_MASK));
            pasteItem.addActionListener(this);
            pasteItem.addKeyListener(this);
            mEdit.add(pasteItem);
            return menuBar;
        public void actionPerformed(ActionEvent e)
            if (e.getActionCommand().equals("Copy"))
                output.selectAll();
                output.copy();
            else if (e.getActionCommand().equals("Paste"))
                output.selectAll();
                output.paste();
            else
                //  performAction(e.getActionCommand());
        public void keyPressed(KeyEvent e)
            if (e.equals(KeyStroke.getKeyStroke
                    (KeyEvent.VK_C, ActionEvent.CTRL_MASK)))
                output.selectAll();
                output.copy();
            else if (e.equals(KeyStroke.getKeyStroke
                    (KeyEvent.VK_V, ActionEvent.CTRL_MASK)))
                output.selectAll();
                output.paste();
    }

    Actually I was wrong sorry, I just realized while doing other stuff (scientific option). I only changed the code in KeyListener and not in ActionListener.
    The above works perfectly:
    public void actionPerformed(ActionEvent e)
            if (e.getActionCommand().equals("Copy"))
                output.setEditable(true);
                output.selectAll();
                output.copy();
                output.setEditable(false);
            else if (e.getActionCommand().equals("Paste"))
                output.setEditable(true);
                output.selectAll();
                output.paste();
                output.setEditable(false);
        // and same for KeyListener
    public void keyPressed(KeyEvent e)
    }As far as JTextField.copy(); and paste(), it does the from the system clipboard under-the-hood.
    void javax.swing.text.JTextComponent.copy()
    Transfers the currently selected range in the associated text model to the system clipboard, leaving the contents in the text model. The current selection remains intact. Does nothing for null selections.
    See Also:
    java.awt.Toolkit.getSystemClipboard
    java.awt.datatransfer.Clipboard
    Edited by: Gcampton on Sep 19, 2010 12:31 AM-
    Thanks to everyone for your help.

  • Disable paste with mouse 3 in Openbox

    Hey guys, I'm trying to disable the feature that Mouse 3 acts as a paste. It's really annoying because two fingers on my touchpad (synaptics driver) will paste something, often when I'm focusing on an input field, sometimes with huge chunks of text. I tried editing my xorg to replace it with left-click, but I can't seem to get it working. What is the most elegant solution for this?

    @Awebb
    Dunno, i just know that rc.conf for modules setting & daemon etc. I was battling with middle click issue before and finally got solved using xmodmap

  • Keyboard not disabling past 180 Degrees (Yoga 13)

    The keyboard on my Yoga 13 is (apparently ouf of the blue) not disabling when I open the Yoga passed 180 degrees.  It doesn't shut off until the Yoga is nearly fully folded back on itself (tablet mode).  This is a big problem for me as I love using the Yoga in stand mode on my lap when sitting in my recliner.
    Any way to adjust this?

    hi slydog75,
    Thanks for Posting,
    I personally would suggest
    Going into Device Manager and uninstall the Drivers under Sensors
    Then Restart the computer the reopen device manager see If the sensors are back then try the Keyboard again
    There is a similar discussion about this issue as well Please Check as some Suggest was able to fix this issue.
    http://forums.lenovo.com/t5/IdeaPad-IdeaTab-Slate-​Tablets/Yoga-13-keyboard-not-turning-off-until-alm​...
    Best Regards
    Solid Cruver
    Did someone help you today? Press the star on the left to thank them with a Kudo!
    If you find a post helpful and it answers your question, please mark it as an "Accepted Solution"! This will help the rest of the Community with similar issues identify the verified solution and benefit from it.
    Follow @LenovoForums on Twitter!

  • Disabling paste option for textfield

    how to disable only ctrl+v option for a textfield.?

    Thanx for the link.
    However, i'm working on swt components.Same principle applies I suppose. Note that SWT might be better discussed in an SWT forum, since it's not part of the standard Java libs.
    I've applied Verfify Keylistener, but i'm not able to
    stop ctrl+v activity.You also won't stop CTRL+INS activity or insertion by mouse context menu... listeners aren't really the best approach.

  • How to disable Copy/Paste to a field in Siebel 7.8

    Hi Gurus,
    Is there a way to disable paste into a certain field in Siebel 7.8?There is a way to do that in normal HTML but is it possible in Siebel.

    One option that comes to mind is to intercept the HTML that is generated for the field on the applet and append to it with the HTML/Javascript that would prevent the pasting.
    For example on the login applet we put some code in capture the enter key since it did not work out of the box.
         if (ControlName == "Password" && Property == "FormattedHtml")
              //onkeypress='JavaScript:null'
              var iOnKeyPressLoc = HTML.indexOf("onkeypress='JavaScript:null'");
              if (iOnKeyPressLoc > 0)
                   //.... REMOVED FOR DISPLAY ....               
                   HTML = sLeftHTML + " " + sMidHTML + " " + sRightHTML;
         }

  • HT4753 how do i disable the saving of past versions to save space?

    how do i disable the saving of past versions to save space?
    i realized that there have been many versions of the file and to save space, i wish to del or disable this function. anyway to do that?
    http://support.apple.com/kb/ht4753

    The question was if there is a way to disable past versions, not how to save a file. I too would like to know the answer to this.

  • Call parking copy and paste issue

    After updating our Lync clients we have run into an issue where the lips emoticon is pasted into the IM windows instead of the actual link containing the parked call to pick up. Previously there was no emoticon for the ":*" string but that is now
    the lips emoticon where previously it was the "(k)" string. When pasting the parked call link, this is the unformatted text showing the first portion of the string containing the :* which is interpreted as the lips.
    tel:*244;ms-parked-call=34633135643133302D656261332D343233632D623830612D6331356334323261363332623B66726F6D2D7461673D326134663330653432313B746F2D7461673D37363335366431323966;phone-context=<client site>
    Disabling Emoticons in the Lync client doesn't help at all.  Even though they are disabled, pasting the content into the composition pane still produces the lips but when sending it shows the text :* and the rest of the string is gone.

    Hi,
    When I copied the orbit number and entered on my Lync 2013 client I got the same result.
    Since a prefix can be the value * or # placed at the beginning of the number, you can create a new callparkorbit policy with the value “#” placed at the beginning of the number.
    You can refer to the link below of “New-CsCallParkOrbit”:
    http://technet.microsoft.com/en-us/library/gg398936.aspx
    Best Regards,
    Eason Huang
    Eason Huang
    TechNet Community Support

  • Cursor invisible in JTextField

    Hi,
    I have tried disabling and making JTextField uneditable separately.
    Text if navigable but the cursor is invisible. Any solution ?

    Hi,
    I have tried disabling and making JTextField uneditable separately.
    Text if navigable but the cursor is invisible. Any solution ?

  • Prevent user from entering info in a JTextField

    I have implemented a calculator in a GUI.
    At the moment it works but the user can enter text in the answer JTextField.
    I want the answer to appear in a JTextField (background to appear grey) when a Jbutton 'equals' is pressed but I want to prevent the user from being able to enter anything in this field, so that it is only an output field. Is there a special way to disable input from JTextFields?
    Thanks in advance!

    Is there a special way to
    disable input from JTextFields?Take a look at:
    setEditable(false); and
    setEnabled(false);
    /Kaj

Maybe you are looking for

  • Self assigned IP??? Don't know how to fix

    My airport keeps self assigning an IP address, I've tried rebooting PRAM, manually entering router and Ip address, deleting system preferences files, renewing DHCP lease, deleting airport, reconfiguring internet settings and airport settings and rebo

  • Adobe Reader 11.0.06 and Windows 8

    Anyone else experiencing issues, attempting to get Reader update v 11.0.06, onto 'Windows 8' SCCM Clients? Eventually got all third party prerequisites installed on Win8 SCCM Clients; used PowerShell for Trusted Publisher/Root entry. Reader update v

  • Is asha 311 reads pdf n word files?

    hey how can i read pdf and word files.I need it pls.....

  • Update statement using case

    Hello my friends I have one table "encompasses": continent,country,percentage now the update should change the continent field, all "Europe" to "Asia" and all "Asia" to "America" and "America" to "Europe" by using case and just one update statement.

  • Creating a trunk to Router Kills Connectivity

    Hi All, have set up 2 routers/2 switches. SW1(3500-192.168.168.2) connects to R1(2600-192.168.168.1) via network 192.168.168.0 and R1(192.168.169.2) connects to R2(2600-192.168.169.1) via network 192.168.169.0. SW2(3500-192.168.167.2) is connected to