uehaj's blog

Grな日々 - GroovyとかGrailsとかElmとかRustとかHaskellとかReactとかFregeとかJavaとか -

ClipBoardWriterってのを作った

marsさんの記事を見て作ったClipBoardWriter。こんな風に使います。

new ClipBoardWriter().withPrintWriter { pw ->
  ['あ', 'い', 'う', 'え', 'お' ].each {
    pw.println it
  }
}

出力したデータがクリップボードにコピーされます。クラス定義はこちら。

import java.io.*;
import java.awt.*
import java.awt.datatransfer.*

class ClipBoardWriter extends Writer {

  private StringWriter buf = new StringWriter()

  public void write(char[] cbuf, int off, int len) throws IOException
  {
      buf.write(cbuf, off, len)
  }

  public void flush() throws IOException {
  }

  public void close() throws IOException {
      def clipboard = Toolkit.defaultToolkit.systemClipboard
      def contents = new StringSelection(buf.toString())
      clipboard.setContents(contents, contents)
  }

  def withPrintWriter(Closure closure)  {
      def pw = new PrintWriter(this)
      closure.call(pw)
      pw.close()
  }
}

さらにいうと、System.outならぬSystem.clipboardOutがstaticにすでに定義されてるといいなあ。そうなると入力が可能なSystem.clipboardInも欲しくなります。で、ギリアムに送ってGDKに追加して欲しいです。勝手にやるにはSystem.metaClass.staticに追加すればいいわけだけれども。