Java Swing Menu showRCMenu(JTextComponent text, MouseEvent e)

Here you can find the source of showRCMenu(JTextComponent text, MouseEvent e)

Description

show RC Menu

License

Open Source License

Declaration

private static void showRCMenu(JTextComponent text, MouseEvent e) 

Method Source Code


//package com.java2s;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.text.*;

public class Main {
    private static void showRCMenu(JTextComponent text, MouseEvent e) {
        int selStart = text.getSelectionStart();
        int selEnd = text.getSelectionEnd();

        JPopupMenu rightClickMenu = new JPopupMenu();

        JMenuItem copyMenuItem = new JMenuItem(text.getActionMap().get(DefaultEditorKit.copyAction));

        JMenuItem cutMenuItem = new JMenuItem(text.getActionMap().get(DefaultEditorKit.cutAction));

        JMenuItem pasteMenuItem = new JMenuItem(text.getActionMap().get(DefaultEditorKit.pasteAction));

        JMenuItem selectAllMenuItem = new JMenuItem(text.getActionMap().get(DefaultEditorKit.selectAllAction));

        copyMenuItem.setText("Copy");
        cutMenuItem.setText("Cut");
        pasteMenuItem.setText("Paste");
        selectAllMenuItem.setText("Select All");

        rightClickMenu.add(copyMenuItem);
        rightClickMenu.add(cutMenuItem);
        rightClickMenu.add(pasteMenuItem);
        rightClickMenu.addSeparator();//w w w  .j  a  va 2s  .  c o m
        rightClickMenu.add(selectAllMenuItem);

        if (text.getText().isEmpty()) {
            copyMenuItem.setEnabled(false);
            selectAllMenuItem.setEnabled(false);
            cutMenuItem.setEnabled(false);
        }

        if (selStart == selEnd) {
            copyMenuItem.setEnabled(false);
            cutMenuItem.setEnabled(false);
        }

        if ((selStart + selEnd) == text.getText().length()) {
            selectAllMenuItem.setEnabled(false);
        }

        if (!text.isEditable()) {
            cutMenuItem.setEnabled(false);
            pasteMenuItem.setEnabled(false);
        }

        rightClickMenu.show(text, e.getX(), e.getY());
    }
}

Related

  1. setMenuFont(Object item, Font theFont)
  2. setMenuText(AbstractButton item, String text, boolean useMnemonic)
  3. setMenuUp(boolean s, JComponent c)
  4. setViewportMenu(JComponent c)
  5. showContextMenu()
  6. toMenu(List actions)