Tuesday, 10 January 2012

Memory Pie Chart (Scala, JavaFX2)

Another simple code snippet using Scala and JavaFX2: A memory visualiser..
package org.mychart

import javafx.application.Application

import javafx.scene.control.Label
import javafx.scene.Scene
import javafx.scene.paint.Color
import javafx.scene.layout.BorderPane
import javafx.stage.Stage
import javafx.scene.chart.PieChart
import javafx.collections.FXCollections
import javafx.scene.layout.Pane

sealed class RealtimeMemory extends Application {
  val timer = new java.util.Timer
  val usedMemData = new PieChart.Data("Used", 0.0)
  val freeMemData = new PieChart.Data("Free", 0.0)
//  val totalMemData = new PieChart.Data("Total", 0.0)
  val pieChartData = FXCollections.observableArrayList(usedMemData, freeMemData)
  val chart = new PieChart(pieChartData)
  val southPane = new Pane
  val southLabel = new Label
  
  override def start(stage: Stage) = {
    val borderPane = new BorderPane
    val scene = new Scene(borderPane, 800, 600, Color.BEIGE)
    stage.setTitle("JFX Xiphias Pricing Client")
    stage.setScene(scene)
    chart.setLabelsVisible(true)
    chart.setLegendVisible(false)
    borderPane.setCenter(chart)
    borderPane.setBottom(southPane)
    
    southPane.getChildren.addAll(southLabel)
    
    stage.show
    
    timer.schedule(new HeapSnapshotTask, 0L, 1000L)
  }
  
  def runInJFXThread(f: () => Unit) = 
    javafx.application.Platform.runLater( new Runnable() { def run() {f()} } )
  
  sealed class HeapSnapshotTask extends java.util.TimerTask {
    override def run = {
      val r = Runtime.getRuntime
      val totalMemory = r.totalMemory / 1024 / 1024 
      val freeMemory = r.freeMemory / 1024 / 1024
      val maxMemory = r.maxMemory / 1024 / 1024
      val usedMemory = totalMemory - freeMemory
      
      usedMemData.setPieValue(usedMemory)
      freeMemData.setPieValue(freeMemory)
//      totalMemData.setPieValue(totalMemory)
      
      runInJFXThread(()=>southLabel.setText(
          "Max: " +maxMemory+", Used:"+usedMemory+
          ", Free:"+freeMemory+", Total:"+totalMemory))
    }
  }
}

object RealtimeMemory {  
  def main(args: Array[String]): Unit = {
    javafx.application.Application.launch(classOf[RealtimeMemory])
  }
}


No comments:

Blog Archive