问题
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.
}
}
});
}
}
}
回答1:
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:
- JTextArea#copy
- JTextArea#cut
- JTextArea#past
- JTextArea#selectAll
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
来源:https://stackoverflow.com/questions/27261759/need-help-implementing-mouselistener-in-jtextarea