Java Swing - Using same Cut Copy Paste Text Actions for Right Click Menu and Menu Bar

[Updated: Jul 14, 2018, Created: Jul 14, 2018]

Following example shows how to share cut/copy/paste actions between right click context menu and JMenuBar.


package com.logicbig.example.common;

import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.JTextComponent;
import javax.swing.text.TextAction;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

public class CutCopyPastActionSupport {
  private JMenu jMenu;
  JPopupMenu popupMenu = new JPopupMenu();

  public CutCopyPastActionSupport() {

  private void init() {
      jMenu = new JMenu("Edit");
      addAction(new DefaultEditorKit.CutAction(), KeyEvent.VK_X, "Cut" );
      addAction(new DefaultEditorKit.CopyAction(), KeyEvent.VK_C, "Copy" );
      addAction(new DefaultEditorKit.PasteAction(), KeyEvent.VK_V, "Paste" );

  private void addAction(TextAction action, int key, String text) {
              KeyStroke.getKeyStroke(key, InputEvent.CTRL_DOWN_MASK));
      action.putValue(AbstractAction.NAME, text);
      jMenu.add(new JMenuItem(action));
      popupMenu.add(new JMenuItem(action));

  public void setPopup(JTextComponent... components){
      if(components == null){
      for (JTextComponent tc : components) {

  public JMenu getMenu() {
      return jMenu;

Main class

public class CutCopyPasteExampleMain {
  public static void main(String[] args) {
      JTextArea ta = new JTextArea(5, 5);
      JTextField tf = new JTextField();
      ta.setText("The coding noses celebrated hours");
      tf.setText("random text");

      CutCopyPastActionSupport support = new CutCopyPastActionSupport();
      support.setPopup(ta, tf);

      JMenuBar menuBar = new JMenuBar();
      JFrame frame = createFrame("Cut Copy Paste Menu Example");

      frame.add(tf, BorderLayout.NORTH);
      frame.add(new JScrollPane(ta));

  public static JFrame createFrame(String title) {
      JFrame frame = new JFrame(title);
      frame.setSize(new Dimension(800, 700));
      return frame;


Right click menu and menu bar show all actions. Shortcut keys work as well.

Example Project

Dependencies and Technologies Used:

  • JDK 10
  • Maven 3.5.4

JTextComponent cut/copy/paste menu example. Select All Download
  • swing-shared-cut-copy-paste
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • common

    See Also