java文本复制粘贴功能代码
时间: 2023-07-10 19:37:44 浏览: 215
以下是Java Swing中实现文本复制粘贴功能的示例代码:
```java
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;
public class TextCopyPasteExample extends JFrame {
private JTextArea textArea;
private JPopupMenu popupMenu;
private JMenuItem copyItem;
private JMenuItem pasteItem;
public TextCopyPasteExample() {
// 创建文本区域
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
getContentPane().add(scrollPane, BorderLayout.CENTER);
// 创建弹出菜单
popupMenu = new JPopupMenu();
copyItem = new JMenuItem("复制");
pasteItem = new JMenuItem("粘贴");
popupMenu.add(copyItem);
popupMenu.add(pasteItem);
// 添加菜单项的事件监听器
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyText();
}
});
pasteItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pasteText();
}
});
// 添加弹出菜单的触发器
textArea.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
});
// 设置窗口属性
setTitle("文本复制粘贴示例");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
// 显示弹出菜单
private void showPopupMenu(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
// 复制文本到剪切板
private void copyText() {
StringSelection selection = new StringSelection(textArea.getSelectedText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
}
// 从剪切板粘贴文本
private void pasteText() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String text = (String) contents.getTransferData(DataFlavor.stringFlavor);
textArea.replaceSelection(text);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new TextCopyPasteExample();
}
}
```
该示例中创建了一个JFrame窗口,并在其中添加了一个JTextArea文本区域,通过添加鼠标事件监听器,在鼠标右键点击时弹出复制粘贴的弹出菜单。在复制和粘贴的方法中,通过Java提供的Clipboard类和Transferable接口实现将文本复制到剪切板和从剪切板中粘贴文本的功能。
阅读全文