How to cut/copy/paste text to JTextField when some JComponent is clicked?

7.1k views Asked by At

I'm creating custom popup menu, using just extended JComponent as a menu items and extended JWindow to hold them. My question is - how to send signal from JComponent instance when it's clicked (has MouseListener) to JTextField to perform cut/copy/paste actions?

EDIT:

I will try to explain more precisely.

JTextField class (simplified):

public class TextInputField extends JTextField implements FocusListener {

        private MenuPopupWindow popUp;

        public TextInputField() {


           popUp = new MenuPopupWindow();//MenuPopupWindow class extends JWindow

           MenuItem paste = new MenuItem("Paste", 
                                         new ImageIcon(getClass().getResource("/images/paste_icon.png")),
                                         "Ctrl+V");//MenuItem class extends JComponent, has implemented MouseListener - and when mouseClicked(MouseEvent e) occurs, somehow action signal have to be sent to this class
            MenuItem copy = ....
            MenuItem cut = ....


            Action pasteAction = getActionMap().get(DefaultEditorKit.pasteAction);
            paste.setAction(pasteAction);//How to make it to work?


            popUp.addMenuItem(paste);
            popUp.addMenuItem(cut);
            popUp.addMenuItem(copy);

        }
        }

How to do it right?

3

There are 3 answers

6
AudioBubble On BEST ANSWER

In light of your posted code, I think all you need to do in your TextInputField class, is add:

paste.addActionListener(pasteAction);

then in your MenuItem class you have to put in code to call those action listeners.

public class MenuItem implements MouseListener
{
    ...
    @Override public void mouseClicked(MouseEvent event)
    {
        ActionListener[] listeners = (ActionListener[])
            MenuItem.this.getListeners(ActionListener.class);
        for(int i = 0; i < listeners.length; i++)
        {
            listeners[i].actionPerformed
            (
                new ActionEvent(MenuItem.this,someID, someCMDName)
            );
        }
    }

In your class that extends JComponent (I'll call it class 'A') you will need to get a reference to your JTextField. A simple way to do this is to add a private instance variable of type JTextField to class A, and pass in the JTextField through the constructor.

so your class should look something like this:

public class A extends JComponent implements ActionListener
{
    private JTextField updateField;

    public A(JTextField updateField[,<your other contructor arguments>...])
    {
        this.updateField = updateField;
        this.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource().equals(this)
        {
            //copy, paste or do whatever with the JTextField
            //by way of this.updateField;
            //e.g. this.updateField.setText(...);
            //or to simply pass the event along to the JTextField's handlers
            //this.updateField.dispatchEvent(event);
        }
    }
}

then you just have to remember to pass the jtextField into the constructor when you create your component

2
camickr On

I'm creating custom popup menu, using just extended JComponent as a menu items and extended JWindow to hold them.

Not really sure what all that means.

You should just use a JPopupMenu and add JMenuItems to it. Read the section from the Swing tutorial on Bringing Up a Popup Menu for an example.

Then, if you want cut/copy/paste functionality, you can use the default actions provided by the DefaultEditorKit:

popup.add( new JMenuItem(new DefaultEditorKit.CopyAction()) );
0
Ernestas Gruodis On

So my working example follows (simplified):

    public class TextInputField extends JTextField {

    private MenuPopupWindow popUp;
    private MenuItem copy,
            cut,
            paste,
            selectAll;

    public TextInputField() {

        popUp = new MenuPopupWindow();

        paste = new MenuItem(this, "Paste", new ImageIcon(getClass().getResource("/images/Paste-icon.png")), "Ctrl+V");
        cut = new MenuItem(this, "Cut", new ImageIcon(getClass().getResource("/images/Cut-icon.png")), "Ctrl+X");
        copy = new MenuItem(this, "Copy", new ImageIcon(getClass().getResource("/images/Copy-icon.png")), "Ctrl+C");
        selectAll = new MenuItem(this, "Select All", null, "Ctrl+A");

        popUp.addMenuItem(paste);
        popUp.addMenuItem(cut);
        popUp.addMenuItem(copy);
        popUp.addMenuItem(selectAll);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                if (SwingUtilities.isRightMouseButton(e)) {

                    if (getSelectedText() == null) {
                        copy.setEnabled(false);
                        cut.setEnabled(false);
                    } else {
                        copy.setEnabled(true);
                        cut.setEnabled(true);
                    }

                    if (getText().equals("")) {
                        selectAll.setEnabled(false);
                    } else {
                        selectAll.setEnabled(true);
                    }

                    Clipboard c = getToolkit().getSystemClipboard();

                    Transferable t = c.getContents(this);

                    if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {

                        String s;

                        try {
                            s = (String) t.getTransferData(DataFlavor.stringFlavor);
                            if (s.equals("")) {
                                paste.setEnabled(false);
                            } else {
                                paste.setEnabled(true);
                            }
                        } catch (UnsupportedFlavorException | IOException ex) {
                            Logger.getLogger(TextInputField.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    } else {
                        paste.setEnabled(false);
                    }

                    popUp.setLocation(e.getXOnScreen(), e.getYOnScreen());
                    getCaret().setVisible(false);
                    popUp.setVisible(true);
                } else {
                    Object obj = e.getSource();
                    if (obj instanceof MenuItem) {
                        MenuItem menuItem = (MenuItem) obj;
                        if (paste == menuItem) {
                            paste();
                        } else if (cut == menuItem) {
                            cut();
                        } else if (copy == menuItem) {
                            copy();
                        } else if (selectAll == menuItem) {
                            selectAll();
                        }
                    }

                    getCaret().setVisible(true);
                    popUp.setVisible(false);
                }
            }
        });
   }
}

And at MenuItem class added (simplified):

@Override
public void mouseClicked(MouseEvent e) {
    textField.dispatchEvent(e);
}

Works superb :)

Decided to use Component instead of JComponent in MenuItem class, because there is no need for paintComponent, paintBorder and paintChildren constructors - saving resources.