需要帮助在JTextArea中实现mouselistener [英] Need help implementing mouselistener in JTextArea
问题描述
大家好,我正在使用JTextArea在Java swing中编写一个简单的gui编辑器.但现在我希望能够右键单击并具有剪切,复制,粘贴和选择所有字体以及可能更改字体的选项.在实现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.
}
}
});
}
}
}
推荐答案
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.
接下来,看看:
现在,如果您真的很聪明,您可以提取关联的Action
,以便JTextArea
的键绑定的复制/剪切/粘贴操作将您自己的Action
包裹在它们周围,并将它们应用于您的JPopupMenu
并免费获得所有内容...
Now, if you're really clever, you would extract the associated Action
s for the copy/cut/paste operations of the JTextArea
s key bindings are wrap your own Action
around them, appling those to your JPopupMenu
and get it all for free...
例如...
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");
这篇关于需要帮助在JTextArea中实现mouselistener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!