Eclipseのプラグイン開発のSWTのクリップボードについて。
|
SWTでは、org.eclipse.swt.dnd.Clipboardクラスでクリップボードを扱う。
テキストとHTMLでクリップボードにコピーする例。
import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.HTMLTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer;
public void copyToClipboard(String text) {
String html = "<b>" + text + "</b>";
Object[] data = { text, html };
Transfer[] dataTypes = { TextTransfer.getInstance(), HTMLTransfer.getInstance() };
Clipboard clipboard = new Clipboard(null);
try {
clipboard.setContents(data, dataTypes);
} finally {
clipboard.dispose();
}
}
ClipboardのコンストラクターにはDisplayオブジェクトを渡す。
古いバージョンのSWTだとnullを渡すと駄目だったようだが、Eclise4.2のSWTは大丈夫だった。
setContents()でクリップボードにデータをセット(コピー)する。
第1引数でデータそのもの、第2引数でデータの種類を指定する。
それぞれ配列になっているので、複数種類のデータをクリップボードに保存することが出来る。
クリップボードからHTMLまたはテキストを取り出す例。
(クリップボードから値を取り出すだけなので、貼り付け(ペースト)ではないが^^;)
import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.HTMLTransfer; import org.eclipse.swt.dnd.TextTransfer;
public String getHtmlFromClipboard() {
Clipboard clipboard = new Clipboard(null);
try {
String html = (String) clipboard.getContents(HTMLTransfer.getInstance());
if (html != null) {
return html;
}
String text = (String) clipboard.getContents(TextTransfer.getInstance());
if (text != null) {
return "<i>" + text + "</i>";
}
} finally {
clipboard.dispose();
}
return null;
}
データの種類を指定してgetContents()を呼び出す。
自分が解釈できる種類を順次試していく。