5

I am using Netbeans to develop an application that will be used in Windows. I noticed I can't right-click to copy or paste. How can I enable this? (I am using basic Swing controls such as JText and JTextArea.)

tobiasbayer
  • 10,269
  • 4
  • 46
  • 64
averageman
  • 893
  • 3
  • 12
  • 19

5 Answers5

13

Why right click is not working on java application?

I wouldn't create new copy, cut, paste, undo & select all actions, because those already exist inside the ActionMap of each component. I'd simply do:

 Action copyAction = textField.getActionMap().get("copy");
 Action cutAction = textField.getActionMap().get("cut");
 Action pasteAction = textField.getActionMap().get("paste");
 Action undoAction = textField.getActionMap().get("undo");
 Action selectAllAction = textField.getActionMap().get("selectAll");


 popup.add (undoAction);
 popup.addSeparator();
 popup.add (cutAction);
 popup.add (copyAction);
 popup.add (pasteAction);
 popup.addSeparator();
 popup.add (selectAllAction);

 return popup;

That way you don't recreate more code that's already written. Other than that I'd follow that example.

Community
  • 1
  • 1
chubbsondubs
  • 37,646
  • 24
  • 106
  • 138
  • Does it interact with the operating system? I want to copy something from my Java application and paste on Notepad... – averageman Jan 26 '12 at 16:32
  • 1
    Yes. The default actions use the System's clipboard class so copying and pasting between any app works in Java Swing. – chubbsondubs Jan 26 '12 at 16:38
  • A more expanded and extensible example of the above can be found here: http://stackoverflow.com/a/11915456/549510 – Kingsolmn Aug 11 '12 at 14:23
  • 4
    Although this can work (not for me), I would use constants instead of strings, because the string can change. For example, in my environment, your code doesn't work (the strings would be `"copy-to-clipboard"`, `"paste-from-clipboard"`, etc). So, instead of `"copy"` use the constant `DefaultEditorKit.copyAction` (and so on). – José Ramón Sep 03 '13 at 11:07
  • how to customize the copy, past and cut ? I want to copy/past some modeled objects (model of entities for example ) ? – Aguid Apr 18 '17 at 07:54
  • If you want to copy and paste complex objects then you'll have to create those Actions yourself. You can place those complex objects in a different mime-type and continue to allow copy/paste to use the traditional Text mine-type so copy/pasting to apps that only accept text to work. It's a little complicated to describe in a comment, but the System clipboard can host several types of data under different mime-types, and that is the key to your request. But the default actions cannot be used to create the complex objects. – chubbsondubs Apr 19 '17 at 14:48
3

Static class to instantly add regular popup menu to a textfield.

Just call JTextFieldRegularPopupMenu.addTo(jTextFieldObj);

import javax.swing.*;
import java.awt.event.ActionEvent;
import javax.swing.JPopupMenu;
import javax.swing.undo.*;


public class JTextFieldRegularPopupMenu {
    public static void addTo(JTextField txtField) 
    {
        JPopupMenu popup = new JPopupMenu();
        UndoManager undoManager = new UndoManager();
        txtField.getDocument().addUndoableEditListener(undoManager);

        Action undoAction = new AbstractAction("Undo") {
            @Override
            public void actionPerformed(ActionEvent ae) {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
                else {
                    JOptionPane.showMessageDialog(null,
                            "Undoable: " + undoManager.canUndo() ,
                            "Undo Status", 
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        };

       Action copyAction = new AbstractAction("Copy") {
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtField.copy();
            }
        };

        Action cutAction = new AbstractAction("Cut") {
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtField.cut();
            }
        };

        Action pasteAction = new AbstractAction("Paste") {
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtField.paste();
            }
        };

        Action selectAllAction = new AbstractAction("Select All") {
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtField.selectAll();
            }
        };

        popup.add (undoAction);
        popup.addSeparator();
        popup.add (cutAction);
        popup.add (copyAction);
        popup.add (pasteAction);
        popup.addSeparator();
        popup.add (selectAllAction);

       txtField.setComponentPopupMenu(popup);
    }
}
Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
1
final int colx;
final int rowy;
final String val1;

colx = CFDTable.getSelectedColumn();
rowy = CFDTable.getSelectedRow();

val1 = (String) CFDTable.getValueAt(rowy, colx);
JPopupMenu jPopupMenu = new javax.swing.JPopupMenu();
jPopupMenu.setName("jPopupMenu");
CFDTable.setComponentPopupMenu(jPopupMenu);
JMenuItem jMenuItem = new javax.swing.JMenuItem();
jMenuItem.setText("Copy"); // NOI18N
jMenuItem.setName("jMenuItem"); // NOI18N
jPopupMenu.add(jMenuItem);

jMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StringSelection entry = new StringSelection(val1);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(entry, entry);
}
});
shruti
  • 11
  • 1
1

For your comment,

Does it interact with the operating system? I want to copy something from my Java application and paste on Notepad..

Why bother the user to manuallly copy-paste, why not write the contents of textarea to a text file?

COD3BOY
  • 11,964
  • 1
  • 38
  • 56
0

Full working model for any JTextComponent including non functional actions and enabling/disabling menu items upon text selection status.

    private JMenuItem composeMenuItemFromActionOfComponent(String actionTag, JComponent component, String text, String idTag){
    Action action = component.getActionMap().get(actionTag);
    JMenuItem menuItem = new JMenuItem(action);
    menuItem.setText(text);
    menuItem.putClientProperty("id",idTag);
    if(action == null)
        menuItem.setEnabled(false);
    return menuItem;
}
private void addTextMenuItems(JTextComponent textField){
    final JPopupMenu popup = new JPopupMenu();
    if(textField.isEditable()) {
        popup.add(composeMenuItemFromActionOfComponent("undo", textField, "Undo", "undo"));
        popup.addSeparator();
    }
    popup.add (composeMenuItemFromActionOfComponent(DefaultEditorKit.copyAction,textField,"Copy", "copy"));
    if(textField.isEditable()) {
        popup.add(composeMenuItemFromActionOfComponent(DefaultEditorKit.cutAction, textField, "Cut", "cut"));
        popup.add(composeMenuItemFromActionOfComponent(DefaultEditorKit.pasteAction, textField, "Paste", "paste"));
        popup.addSeparator();
    }
    popup.add (composeMenuItemFromActionOfComponent(DefaultEditorKit.selectAllAction,textField,"Select All", "select_all"));

    textField.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {}

        @Override
        public void mousePressed(MouseEvent e) {}

        @Override
        public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()) {
                boolean isTextSelected = textField.getSelectedText() != null;
                for(MenuElement element : popup.getSubElements()){
                    JMenuItem menuItem = ((JMenuItem) element);
                    if(menuItem.getAction() != null && menuItem.getAction().isEnabled()) {
                        if (isTextSelected){
                            menuItem.setEnabled(true);
                        }else if (!(menuItem.getClientProperty("id").equals("select_all")
                                || menuItem.getClientProperty("id").equals("undo")))
                            menuItem.setEnabled(false);
                    }
                    if(menuItem.getClientProperty("id").equals("paste")){
                        boolean isPastAvailable = false;
                        for(DataFlavor flavor : Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors()){
                            if(flavor.getRepresentationClass() == String.class){
                                isPastAvailable = true;
                                break;
                            }
                        }
                        menuItem.setEnabled(isPastAvailable);
                    }

                }
                e.getComponent().requestFocus();
                popup.show(e.getComponent(), e.getX(), e.getY());
            }

        }

        @Override
        public void mouseEntered(MouseEvent e) {}

        @Override
        public void mouseExited(MouseEvent e) {}
    });
}
Yan
  • 1,569
  • 18
  • 22