Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - Need help implementing mouselistener in JTextArea

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.
                    }
                }
            });
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...