Skip to content

Instantly share code, notes, and snippets.

@OlegIlyenko
Created April 14, 2012 21:13
Show Gist options
  • Save OlegIlyenko/2387901 to your computer and use it in GitHub Desktop.
Save OlegIlyenko/2387901 to your computer and use it in GitHub Desktop.
import javax.swing.UIManager
import java.net.URL
import java.awt.Dimension
import java.io.Closeable
import swing._
object Downloader extends SimpleSwingApplication {
UIManager.getInstalledLookAndFeels
.filter(_.getName contains "Nimbus").headOption
.map(_.getClassName).foreach(UIManager setLookAndFeel _)
val url = new TextField(35)
val progress = new ProgressBar
val info = new Label("Please start download")
def top = new MainFrame {
title = "File Downloader"
contents = new BoxPanel(Orientation.Vertical) {
contents += new FlowPanel(FlowPanel.Alignment.Right)(
new Label("URL:"),
url,
Button("Download") {
import Util._
thread {
val conn = new URL(url.text).openConnection
val tracker = (p: Progress) => Swing.onEDT {
info.text = "<html>" + p.formattedMetrics.mkString("<br>") +"</html>"
progress.value = p.percent
}
withResource(ProgressInputStream(conn.getInputStream, conn.getContentLength, tracker)) { in =>
val buf = new Array[Byte](1024)
while(in.read(buf) != -1) {
println("Reading 1 kb")
}
}
}
}
)
contents += progress
contents += new FlowPanel(FlowPanel.Alignment.Left)(info)
}
size = new Dimension(550, 250)
centerOnScreen()
}
}
object Util {
def thread(fn: => Unit) = {
val thread = new Thread(Swing.Runnable(fn))
thread.start()
thread
}
def withResource[T <: Closeable, R](res: T)(fn: T => R) =
try {
fn(res)
} finally {
try {
res.close()
} catch {
case e: Exception => e.printStackTrace()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment