廢話不多說,直接上代碼,小伙伴們仔細看下注釋吧。
復制代碼代碼如下:
/*簡單的復制 剪切 粘貼 功能
操作:
復制測試: 輸入文本選擇文本,點擊復制,然后將光標放在右邊的TextArea,點擊粘貼
剪切測試:輸入文本選擇文本,然后將光標放在右邊的TextArea,點擊剪切
*/
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
public class Demo implements ActionListener
{
private JFrame jf;
private JPanel p1, p2, p3; //上中下
private JLabel title;
private JTextArea edit,showMsg;
private JButton copy,paste,cut;
Clipboard clipboard;//獲取系統剪貼板。
public Demo()
{
this.init();
}
//界面初始化
public void init()
{
jf = new JFrame("復制粘貼");
p1 = new JPanel(); //存放標題
p2 = new JPanel(); //存放JTextArea showMsg
p3 = new JPanel(); //存放 button
title = new JLabel("復制粘貼剪切演示");
edit = new JTextArea("請輸入內容",15,25);
edit.setLineWrap(true);
showMsg = new JTextArea(15,25);
showMsg.setLineWrap(true);
showMsg.setEnabled(false);
copy = new JButton("復制");
paste = new JButton("粘貼");
cut = new JButton("剪切");
clipboard = jf.getToolkit().getSystemClipboard();
p1.setLayout(new FlowLayout());
p1.setSize(599,30);
p1.add(title);
p2.setLayout(new FlowLayout());
p2.setBackground(Color.gray);
p2.add(edit);
p2.add(showMsg);
p3.setLayout(new FlowLayout());
p3.add(copy);
p3.add(paste);
p3.add(cut);
//添加事件監聽機制
copy.addActionListener(this);
paste.addActionListener(this);
cut.addActionListener(this);
// this.copyStr(copy);
jf.add(p1, BorderLayout.NORTH);
jf.add(p2, BorderLayout.CENTER);
jf.add(p3, BorderLayout.SOUTH);
jf.setLocation(400,200);
jf.setSize(600,450);
jf.setResizable(false);
jf.setVisible(true);
}
//事件處理
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == copy)
{
String tempText = edit.getSelectedText(); //拖動鼠標選取文本
//創建能傳輸指定 String 的 Transferable。
StringSelection editText =
new StringSelection(tempText);
/**
將剪貼板的當前內容設置到指定的 transferable 對象,
并將指定的剪貼板所有者作為新內容的所有者注冊。
*/
clipboard.setContents(editText,null);
}else if(e.getSource() == cut)
{
String tempText = edit.getSelectedText();
StringSelection editText =
new StringSelection(tempText);
clipboard.setContents(editText,null);
int start= edit.getSelectionStart();
int end = edit.getSelectionEnd();
showMsg.replaceRange("",start,end) ; //從Text1中刪除被選取的文本。
}else if(e.getSource() == paste)
{
Transferable contents = clipboard.getContents(this);
DataFlavor flavor= DataFlavor.stringFlavor;
if( contents.isDataFlavorSupported(flavor))
{
try
{
String str;
str = (String)contents.getTransferData(flavor);
showMsg.append(str);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
public static void main(String[] args)
{
new Demo();
}
}
代碼很簡單,使用也很方便,小伙伴們有更好的思路的話,請一定要告訴我。