From fd040af74fa27ee7491243ebb4900166cd0c1005 Mon Sep 17 00:00:00 2001 From: Sarah Gerweck Date: Sat, 4 Jun 2016 00:32:00 -0700 Subject: [PATCH] New class for making singleton windows This ensures there will be at most one copy of the stage, which will be created and destroyed as needed. Trying to create a second just brings the first into focus. This is good for things like preferences windows. --- .../gerweck/scalafx/util/SingletonStage.scala | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/scala/org/gerweck/scalafx/util/SingletonStage.scala diff --git a/src/main/scala/org/gerweck/scalafx/util/SingletonStage.scala b/src/main/scala/org/gerweck/scalafx/util/SingletonStage.scala new file mode 100644 index 0000000..a7e57b1 --- /dev/null +++ b/src/main/scala/org/gerweck/scalafx/util/SingletonStage.scala @@ -0,0 +1,35 @@ +package org.gerweck.scalafx.util + +import scalafx.stage.Stage + +import org.log4s._ + +/** A stage that should only be open at most once per application. */ +abstract class SingletonStage { + private[this] val logger = getLogger + + type InstanceStage <: ParentStage + + protected[this] var singletonStage: Option[InstanceStage] = None + + def name = getClass.getSimpleName + + protected[this] def makeStage(): InstanceStage + + def showStage(): Unit = { + singletonStage match { + case Some(stg) => + logger.debug("Singleton ${name} stage is already open") + stg.requestFocus() + case None => + val ns = makeStage() + singletonStage = Some(ns) + ns.show() + } + } + + protected trait ParentStage extends Stage { + require(singletonStage.isEmpty, s"Cannot have two ${name} stages") + logger.debug(s"Creating singleton ${name} stage") + } +}