廢話不多說,直接上程式碼,朋友仔細看下註解吧。
複製代碼代碼如下:
/*簡單的複製剪下貼上功能操作:
複製測試: 輸入文本選擇文本,點擊複製,然後將遊標放在右邊的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();
}
}
程式碼很簡單,使用也很方便,小夥伴們有更好的思路的話,請一定要告訴我。