Java 複製文字方法


因為在編寫一個小程式時想要進利文字上的複製.
所以就在網上找到了一個例子,改良了一下,加入到了現在的程式,記錄一下代碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.awt.datatransfer.*;
import java.awt.*;

public class Java2Clipboard implements ClipboardOwner {
public static void main(String[] args) throws Exception {
Java2Clipboard jc = new Java2Clipboard();
jc.toClipboard();
Frame f = new Frame
("Open a text editor and paste the message from Java");
f.setSize(600,10);
f.show();
}

public void toClipboard() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkSystemClipboardAccess();
}
catch (Exception e) {e.printStackTrace();}
}
Toolkit tk = Toolkit.getDefaultToolkit();
StringSelection st =
new StringSelection("Hello world from Java");
Clipboard cp = tk.getSystemClipboard();
cp.setContents(st, this);
}

public void lostOwnership(Clipboard clip, Transferable tr) {
System.out.println("Lost Clipboard Ownership?!?");
}
}