Search code examples
javaswingjtextfieldkey-bindingsjpopupmenu

Paste menu item, not doing anything when attached to a JTextField


I have a JTextField, paste automatically works using Cntl-V because of inbuilt support within Swing. But I additionally need a popupmenu to help users not so familiar with shortcut keys. The following code

import javax.swing.*;
import java.awt.*;

public class TestPopup
{
    public static void main(final String[] args)
    {
        JFrame frame = new JFrame();
        JTextField widget      = new JTextField(50);
        final JPopupMenu popup = new JPopupMenu();
        popup.add(widget.getActionMap().get("paste"));
        widget.add(popup);
        widget.setComponentPopupMenu(popup);
        frame.add(widget);
        frame.pack();
        frame.setVisible(true);
    }
}

displays the paste option but does nothing when selected. Also note is is displayed as 'paste' rather than 'Paste'

What am I doing wrong ?

* Solution *

Nevermind, got it working, using DefaultEditorKit.pasteAction instead of "paste" makes the paste works, (unclear to me what the "paste" action actually does as it exists)

import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;

public class TestPopup
{
    public static void main(final String[] args)
    {
        JFrame frame = new JFrame();
        JTextField widget      = new JTextField(50);
        final JPopupMenu popup = new JPopupMenu();
        popup.add(widget.getActionMap().get(DefaultEditorKit.pasteAction));
        widget.add(popup);
        widget.setComponentPopupMenu(popup);
        frame.add(widget);
        frame.pack();
        frame.setVisible(true);
    }
}

but this will not fix the name problem, to do this I introduced menu item

import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;

public class TestPopup
{
    public static void main(final String[] args)
    {
        JFrame frame = new JFrame();
        JTextField widget      = new JTextField(50);
        final JPopupMenu popup = new JPopupMenu();
        JMenuItem pasteMenuItem = new JMenuItem(widget.getActionMap().get(DefaultEditorKit.pasteAction));
        pasteMenuItem.setText("Paste");
        popup.add(pasteMenuItem);

        widget.setComponentPopupMenu(popup);
        frame.add(widget);
        frame.pack();
        frame.setVisible(true);
    }
}

Solution

  • It may help to notice that DefaultEditorKit.pasteAction is the name of the Action, "paste-from-clipboard". It may be easier to set the menu item's Action directly:

    JMenuItem pasteMenuItem = new JMenuItem(new DefaultEditorKit.PasteAction());