By Alvin Alexander. Last updated: June 4, 2016
If you need an example of how to use the Java Robot class in a Scala program, here's a quick one. As unusual as it might seem, this example lets your Scala program log back into a Mac OS X computer after you've been logged out, typically by a screensaver.
First, here's the Scala source code to demonstrate the Robot class:
package robot
import java.awt.AWTException
import java.awt.Robot
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
object RobotLogin {
val password = "PASSWORD"
val robot = new Robot
def main(args: Array[String]) {
robot.setAutoDelay(40)
robot.setAutoWaitForIdle(true)
robot.delay(20*1000)
robot.mouseMove(40, 130)
robot.delay(1*1000)
typeString(password)
robot.delay(1*1000)
typeKeystroke(KeyEvent.VK_ENTER)
robot.delay(1000)
System.exit(0)
}
def leftClick {
robot.mousePress(InputEvent.BUTTON1_MASK)
robot.delay(200)
robot.mouseRelease(InputEvent.BUTTON1_MASK)
robot.delay(200)
}
def typeKeystroke(i: Int) {
robot.delay(40)
robot.keyPress(i)
robot.keyRelease(i)
}
def typeString(s: java.lang.String) {
val bytes = s.getBytes
for (b <- bytes) {
var code = b.toInt
// keycode only handles [A-Z] (which is ASCII decimal [65-90])
if (code > 96 && code < 123) code = code - 32
robot.delay(40)
robot.keyPress(code)
robot.keyRelease(code)
}
}
}
Scala Robot class - demo video
Next, here's a video that shows how this source code works:
For more information on using the Robot class, see my original Java Robot class example. Although that source code is written in Java, it probably demonstrates a much more "normal" use case than the example shown here.
Reporting live with creative ideas from beautiful downtown Boulder, Colorado, this is Alvin Alexander.

