October 1, 2013

Add context menu copy/paste to a Java JTextArea

suppose you have the variable "ta" as the textarea:


  ta.addMouseListener(new MouseAdapter() {
   public void mouseReleased(final MouseEvent e) {
    if (e.isPopupTrigger()) {
     final JPopupMenu menu = new JPopupMenu();
     JMenuItem item;
     item = new JMenuItem(new DefaultEditorKit.CopyAction());
     item.setText("Copy");
     item.setEnabled(ta.getSelectionStart() != ta.getSelectionEnd());
     menu.add(item);
     menu.show(e.getComponent(), e.getX(), e.getY());
    }
   }
  });

1 comment: