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());
    }
   }
  });

3 comments:

  1. Work very well, thanks!

    ReplyDelete
  2. It's wonderful to do a search and find exactly what I was looking for! Thank you!

    ReplyDelete
  3. WOW ! Where is the easy button ? Thanks so much for the very elegant code snippet .

    ReplyDelete