-1

Hello guys i am writing a simple gui editor in java swing using JTextArea. but now i want to be able to right click and have the options to cut, copy, paste and select all and possibly change fonts. I need help in implementing the option of cutting, copying or pasting in the JTextArea. Help will be appreciated. Below is a snippet of my code:

public class Example extends JPanel
{
    private JTextArea area;
    private JScrollPane scpane;

    public Example()
    {
        super("My Text Editor");
        setUp();
    }

    private void setUp()
    {
        area = new JTextArea();
        scpane= new JScrollPane(area);

        area.addMouseListener(
            new MouseAdapter()
            {
                public void mousePressed(MouseEvent e)
                {
                    if(e.getButton()==MouseEvent.BUTTON3)
                    {
                        //having difficulty how to set up the copy, cut or paste option 
                        //with the mouse in JTextArea.
                    }
                }
            });
        }
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • *"I need help in implementing the option.."* SO is not a help desk, it is a Q&A Site. Throw 'right click java' into your favorite search engine and follow the 5 top links. Try something yourself. Get back to us when you have a specific *question* and an [MCVE](http://stackoverflow.com/help/mcve) or [SSCCE](http://www.sscce.org/) of your attempt. Voting to close this as 'too broad'. – Andrew Thompson Dec 03 '14 at 00:49

1 Answers1

3

Start by taking a look at JComponent#setComponentPopupMenu which will allow you to associate a JPopupMenu with a component and have it automatically displayed when the user triggers the appropriate, system specific, trigger.

Next, take a look at:

Now, if you're really clever, you would extract the associated Actions for the copy/cut/paste operations of the JTextAreas key bindings are wrap your own Action around them, appling those to your JPopupMenu and get it all for free...

For example...

    JTextArea ta = new JTextArea();
    ActionMap am = ta.getActionMap();

    Action paste = am.get("paste-from-clipboard");
    Action copy = am.get("copy-to-clipboard");
    Action cut = am.get("cut-to-clipboard");

See How to Use Actions and How to Use Key Bindings for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366