EzDevInfo.com

scalafx

ScalaFX simplifies creation of JavaFX-based user interfaces in Scala. ScalaFX • simpler way to use JavaFX from Scala

How can you get ScalaFX to play nice in the SBT console?

I'm writing an image library for intro programming students to play with. (I stole the idea and the patterns from the image library for DrRacket.)

https://github.com/dupontmanualhs/dm-image

It's mostly written in Swing (that's the master branch), but I'm trying to convert it to ScalaFX (see the scalafx branch), and there are some issues. Ideally, a student should be able to do something like:

scala> import org.dupontmanual.image._
scala> TrainEngine.display()

and have a dialog box with a train engine show up. I've tried using the code at

https://github.com/scalafx/ScalaFX-Tutorials

in the stand-alone-dialog project, but if I include System.exit(0) after I dialog.showAndWait(), I get this error:

Not interrupting system thread Thread[process reaper,10,system]
Exception while removing reference: java.lang.InterruptedException
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
    at com.sun.glass.utils.Disposer.run(Disposer.java:69)
    at java.lang.Thread.run(Thread.java:744)
Not interrupting system thread Thread[Prism Font Disposer,10,system]
Exception in runnable
Exception in thread "JavaFX Application Thread"

(Note that I get the same error if I try to run the App from stand-alone-dialog in the console, so I'm guessing that calling System.exit(0) is not a great idea in the SBT console.)

If I leave the System.exit(0) line out, then things seem to work fine--mostly. After the first time I display the dialog, it doesn't bring the dialog into focus, so I have to click it to dismiss the dialog. But the real problem is that when I :q to exit the console, SBT hangs and I have to Ctrl-C to be able to type again. (And, yes, Ctrl-C exits SBT completely, not just the console.)

I think what I may need to do is create a thread specifically for ScalaFX stuff. For example, I have a method to stack one image on top of another, and I got an IllegalStateException when I tried to call that function, even though it doesn't actually display anything, just creates a new Group with the two previous Nodes stacked appropriately. Unfortunately, I'm not sure how to create a new thread and make sure that everything image-related runs through that.

I've already set fork := true in build.sbt, but that doesn't seem to make a difference with the console.

== Update ==

I found initialCommands and cleanupCommands in the SBT documentation and tried to clean up after everything when the console starts and ends. The values are:

initialCommands in console := """import org.dupontmanual.image._; org.dupontmanual.image.initialize()"""

cleanupCommands in console := """org.dupontmanual.image.cleanUp()"""

which are defined thusly:

package object image {
  var masterFrame: JFrame = _

  def initialize() {
    masterFrame = new JFrame()
    masterFrame.add(new JFXPanel())
    masterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
  }

  def cleanUp() {
    println("exiting platform")
    Platform.exit()
    println("disposing of frames")
    Frame.getFrames().foreach {
      _.dispose()
    }
    println("frames all disposed")
    System.exit(0);
  }

Here's the result of running the console and then trying to quit:

> console
[info] Compiling 1 Scala source to /home/sysadmin/dm-workspace/dm-image/target/scala-2.10/classes...
[info] Starting scala interpreter...
[info] 
import org.dupontmanual.image._
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_51).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Hacker.display()

scala> :q
exiting platform
disposing of frames
frames all disposed
Not interrupting system thread Thread[XToolkt-Shutdown-Thread,5,system]
Not interrupting system thread Thread[AWT-XAWT,6,system]
Not interrupting system thread Thread[Prism Font Disposer,10,system]
Not interrupting system thread Thread[Java2D Disposer,10,system]
Exception while removing reference: java.lang.InterruptedException
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
    at com.sun.glass.utils.Disposer.run(Disposer.java:69)
    at java.lang.Thread.run(Thread.java:744)

Exception: sbt.TrapExitSecurityException thrown from the UncaughtExceptionHandler in thread "run-main-0"

and that doesn't even exit the console. You still have to use Ctrl-C, which exits out of SBT completely.

Something is still running, but I can't figure out what it is. Grrr.


Source: (StackOverflow)

Make ScalaFX scene draggable

I am actually working on an ScalaFX application without window decorations. What I want to do is making it draggable, so that a user can move it anyhow.

I managed moving the stage by simply writing the coordinates of the dragging mouse into the stage X/Y coordinates. However, that resulted in a laggy and flickering window.

How can dragging a stage be implemented smoothly in ScalaFX?


Source: (StackOverflow)

Advertisements

JavaFx2 or ScalaFx + Akka

How to run Akka actors in a JavaFX/ScalaFX Application ?

(This is an update of question based on the first answers)

Is the solution to share the same execution context? Meaning having the Actors dispatchers based on the JavaFx ExecutorService ? (The one with which on which it runs UI manipulation code)

Does that mean one agent would represent the UI and be able to manipulate it ? I mean because suggested below if a couple of actor are on the UI ExecutorService, doesn't that mean share a state between agent (the object being the UI)?

Can 2 actors communicate while being on different executor services? I'm asking this because from what is suggested below, some agent would be on the UI Executor Service while other not.

Finally, why using akka as is, with its on Executor context different and using Platform.runLater, might have some consequence on the performance of the UI. I this pose the question of multiple executor service on the same application: Is that bad?


Source: (StackOverflow)

Scala, GUI and immutability

I created an algorithm that calculates certain things. This can be considered as the model. The algorithm is implemented in a fully functional way, so it uses immutable classes only. Now using this model, I would like to develop a GUI layer on the top of it. However I do not know anything about the best-practises of building GUI in Scala. I intend to use ScalaFX.

My problem is the following: in ScalaFX (similarly to JavaFX) you can bind values from the GUI to object properties. This clearly violates the functional paradigm, but seems very convenient. This would require rewriting my classes to use bindable properties which would feel like the tail wagging the dog — the model would depend on the GUI.

On the other hand, I could have an independent GUI layer. In this case I would need proxy objects to bind to and I would have to create my model objects based on these proxy objects. This would feel more idiomatic but implies a lot of code duplication and extra work. My model and the proxy objects would have to be kept in sync and I would have to take care of copying the attributes.

What is a good way of doing this? A GUI is always full of mutability so functional programming does not feel right here. Nevertheless I love Scala so I would like to keep using it for the GUI, too.


Source: (StackOverflow)

What are the benefits of ScalaFX besides adding syntactic sugar for bindings?

I am trying to implement a simple note organizer with some mind mapping functionality using JavaFX and Scala.

I am trying to decide whether I should call JavaFX code directly from Scala or via ScalaFX ? I don't know if it is worth to learn ScalaFX and would it not be just simpler to directly call JavaFX from Scala code?

The official ScalaFX site mentions 4 benefits of ScalaFX:

1) Natural Language Bind Expressions

-It's nice but I don't really plan using bindings that much (I intend to use EventBus for inter--gui-component events and a few bindings for intra-gui-component events).

2) Tailored Animation Syntax

-I don't plan to use animations in my project.

3) Full Type-Safe APIs

This may seem like an insignificant point… Type safety is something that Java developers have always had (and often take for granted), and developers in other scripting languages live without (and unknowingly suffer with runtime errors as a result). However, it is a critical feature if you are developing applications that cannot have unexpected runtime errors and bugs after deployment.

A good compiler will be able to pick up many common coding mistakes through comparison of expected and actual types, and a great compiler (like Scala) will automatically infer types for you so you don’t have to tediouisly repeat them throughout your code.

ScalaFX gets the best of both worlds with a scripting-like DSL syntax where you can rarely have to explicitly type objects, with the strong type-safety of the Scala compiler that will infer and check the types of every expression and API call. This means less time spent debugging weird code bugs and misspellings, and higher quality code right out of the gate!

-This seems interesting ! But my question is: I suspect that calling JavaFX directly from Scala gives me the same type safety guarantees as calling JavaFX via ScalaFX, or not ? I don't know.

4) Seamless JavaFX/ScalaFX interoperability:

-If I call JavaFX directly from Scala then I don't have to worry more about interoperability issues than when calling JavaFX via ScalaFX.

In summary:

It seems that point 3 is the only one that might give me some benefit that I care about in my simple project but I just don't know what kind of type safety they are really talking about ?

Why is it better to call JavaFX via ScalaFX than directly from Scala with respect to type safety ? What kind of additional type safety benefits do we get if we use ScalaFX instead of direct access from Scala ? I am asking this because I cannot really imagine what kind of additional type safety ScalaFX could give ?

So, in other words, I understand that ScalaFX is a nice syntactic sugar for bindings but does it offer more than that ? Should I really use it if I can live without the (very nice) syntac sugar it gives?

Is there something else than the sugar that would make it worth using this wrapper layer (ScalaFX) which introduces extra complexity (and source of bugs) ?

Please note that I really appreciate the work of ScalaFX's creators ! I am only asking these questions to be able to make a better informed decision.


Source: (StackOverflow)

JavaFX / ScalaFX - Change text color of disabled TextArea?

I have a GUI with some TextArea elements to display information. As the GUI shall react to keyevents I added a EventHandler to the scene element. Because I didn't want to add one EventHandler to each textarea I disabled them to prevent that they are focused because then the scene's eventhandler doesn't work anymore. Now I have the problem the text is displayed in gray and not in black anymore eventhough I changed that in the css file. Do you have any ideas why the text isn't black and how i could fix that?

Here is some code:

private val scene =
  new Scene {
    stylesheets.add("css/style.css")
    onKeyTyped = (new EventHandler[KeyEvent] {
      def handle(event: KeyEvent) {
        ...
      }
    })
  ...
}

private val description = new TextArea{    
  text = "some text"
  wrapText = true
  disable = true 
  styleClass.add("txtarea")      
  maxHeight = 400
}


.txtarea:disabled{  
  -fx-font-size: 18pt;
  -fx-text-fill: #000000;
  -fx-prompt-text-fill: #000000;
  -fx-opacity: 1.0;
  -fx-background-color: white;  
}

Source: (StackOverflow)

How do Iaunch a ScalaFX application from Scala?

I'm trying to launch the ScalaFX Hello World application from http://www.scalafx.org with the following code:

package car.cadr

object ApplicationStarter {
    def main(args: Array[String]) =
        javafx.application.Application.launch(classOf[HelloStageDemo], args: _*)
}

To clarify, I have two Scala files in the car.cadr package: ApplicationStarter.scala and HelloStageDemo.scala. HelloStageDemo.scala starts and runs perfectly fine, but the compiler is complaining about not found: type HelloStageDemo on ApplicationStarter.scala. Even if I manually import it with import car.cadr.HelloStageDemo the compiler still complains.

I'm using Scala 2.11.1 and ScalaFx 8.0.20-R6.


Source: (StackOverflow)

binding a function with conditional logic in scala

I am a scala newbie who came from JavaFX 1.3 and this is my first post in stackoverflow

In JavaFX 1.3 I can do something like this

property : bind if (condition) value1 else value2

In Scala, I attempted doing something like this:

property <== function1

def function1() = {
  if (condition)
    value1
  else
    value2
}

However, it does not seem to be dynamically working. The expression in the condition of the function evaluates only once when the stage appears. I was kind of expecting the values in that expression are evaluated in realtime.

Specifically, I want to resize something to a certain limit and I am using binding to achieve it. So I want the bound function to keep evaluating the expression and give me the appropriate width of something as I resize other things.

Anyway, I will paste the actual codes below:

var stageWidth = DoubleProperty(0)
var stageHeight = DoubleProperty(0)

stageWidth <== stage.scene.width
stageHeight <== stage.scene.height

var origStageWidth = DoubleProperty(stage.scene.width.toDouble)
val origStageHeight = DoubleProperty(stage.scene.height.toDouble)

val origTextClipperWidth = DoubleProperty(textClipper.width.toDouble)
val origTextClipperHeight = DoubleProperty(textClipper.height.toDouble)
val minWidth = DoubleProperty(100)

val origButtonWidth = DoubleProperty(button.prefWidth.toDouble)

textClipper.width <== resize

def resize() ={
    var boolResult = (stageWidth - origStageWidth) + origTextClipperWidth > minWidth
    if (boolResult.value) {
        (stageWidth - origStageWidth) + origTextClipperWidth
    } else {
        minWidth
    }
}

textClipper.height <== (stageHeight - origStageHeight) + origTextClipperHeight

Thanks in advance for your help.


Source: (StackOverflow)

A simplest scalafx example can't be compiled

I'm trying the scalafx with a simplest example, but it can't be compiled and the error is like:

Error:scalac: bad symbolic reference to javafx.stage.PopupWindow.AnchorLocation encountered in class file 'StageIncludes.class'. Cannot access type AnchorLocation in object javafx.stage.PopupWindow. The current classpath may be missing a definition for javafx.stage.PopupWindow.AnchorLocation, or StageIncludes.class may have been compiled against a version that's incompatible with the one found on the current classpath.

I googled and found someone say we need to add the jfxrt.jar to classpath, but which is still not working.

My code:

build.sbt

name := "ColaBlog"

version := "0.1.0"

scalaVersion := "2.11.0"

libraryDependencies ++= List(
  "org.scalafx" % "scalafx_2.11" % "8.0.0-R4"
)

unmanagedJars in Compile += Attributed.blank(
  file(scala.util.Properties.javaHome) / "lib" / "jfxrt.jar")

fork in run := true

App.scala

import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.paint.Color
import scalafx.scene.shape.Rectangle

object App extends JFXApp {

  stage = new JFXApp.PrimaryStage {
    title = "Hello World"
    width = 600
    height = 450
    scene = new Scene {
      fill = Color.LIGHTGREEN
      content = Set(new Rectangle {
        x = 25
        y = 40
        width = 100
        height = 100
        fill <== when(hover) choose Color.GREEN otherwise Color.RED
      })
    }
  }
}

That's all.


Source: (StackOverflow)

Scala instantiation of a class with curly braces

I am starting with Scala and with ScalaFX, I understand most of the code but I don't understand this code using for the examples in ScalaFx;

where instantiate an anonymous class follow it by curly braces, How this works???

object ScalaFXHelloWorld extends JFXApp {

  stage = new PrimaryStage {

    title = "ScalaFX Hello World"

    scene = new Scene {

      fill = Black

      content = new HBox {

        padding = Insets(20)

        children = Seq(
          new Text {
            text = "Hello"
            style = "-fx-font-size: 48pt"
            fill = new LinearGradient(
              endX = 0,
              stops = Stops(PaleGreen, SeaGreen)
            )
          },
          new Text {
            text = "World!!!"
            style = "-fx-font-size: 48pt"
            fill = new LinearGradient(
              endX = 0,
              stops = Stops(Cyan, DodgerBlue)
            )
            effect = new DropShadow {
              color = DodgerBlue
              radius = 25
              spread = 0.25

            }
          }
        )

      }

    }

  }

}

the part I don't understand is why in the creation of an anonymous class is follow by curly braces (with some more declarations)(Scene is not a trail to be filling the abstract parts of that class) and even fill or content are functions not a variables and Black for fill for instant is a val meaning that this line

fill = Black

is doing calling a function fill and assigning a val to it(don't make sense for me ), this is fill definition

def fill: ObjectProperty[jfxsp.Paint] = delegate.fillProperty

and this is Black

val Black = new Color(jfxsp.Color.BLACK)

how works this instantiation of a new object with curly braces please help, want to understand. This is because ScalaFx is wrapping JavaFx and something special is going on here?. Thank you guys.

Update:

Well now I know that it is calling a setter via syntax sugar however I check that setter and I don't understand what is going on there

Check it out:

def fill: ObjectProperty[jfxsp.Paint] = delegate.fillProperty
  def fill_=(v: Paint) {
    fill() = v
}

how come the setter is calling the getter to update the value?

delegate.fillProperty

is a function that return a value


Source: (StackOverflow)

Scala name mangling of private fields and JavaFX FXML injection

The following example and explanations are quite long, so here is the gist of my question: how to deal with scalac's name-mangling of private fields when using a framework which insists on performing field injection (on fields which really should stay private)?


I am writing an application in Scala, using ScalaFX/JavaFX and FXML. When you use FXML to define your views in JavaFX, objects defined in FXML (such as buttons and text fields) are injected into the controller by :

  • adding an fx:id property to the FXML elements
  • adding (usually private) fields to the controller, with the @FXML annotation and with field names matching the values of the fx:id properties defined in the FXML
  • when the FXMLoader instantiates the controller, it automatically injects the fx:id annotated elements into the matching @FXML annotated fields of the controller through reflexion

I'm not a big fan of field injection, but that's how FXML works. However, I've run into unexpected complications in Scala, due to field name mangling performed by the compiler in some circumstances...

Here is an example application :

test/TestApp.scala (nothing interesting, just needed to run the example)

package test

import javafx.application.Application
import javafx.fxml.FXMLLoader
import javafx.scene.{Scene, Parent}
import javafx.stage.Stage

object TestApp {
  def main(args: Array[String]) {
    Application.launch(classOf[TestApp], args: _*)
  }
}

class TestApp extends Application {
  override def start(primaryStage: Stage): Unit = {
    val root: Parent = FXMLLoader.load(getClass.getResource("/test.fxml"))
    val scene: Scene = new Scene(root, 200, 200)

    primaryStage.setTitle("Test")
    primaryStage.setScene(scene)
    primaryStage.show()
  }
}

test.fxml (the view)

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>


<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0"
      prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1"
      fx:controller="test.TestController">
    <children>
        <CheckBox fx:id="testCheckBox" mnemonicParsing="false" text="CheckBox"/>
        <Button fx:id="testButton" mnemonicParsing="false" text="Button"/>
    </children>
</VBox>

test/TestController.scala (the controller for the test.fxml view)

package test

import javafx.fxml.FXML
import javafx.scene.{control => jfxsc}

import scalafx.Includes._

class TestController {
  @FXML private var testCheckBox: jfxsc.CheckBox = _
  @FXML private var testButton: jfxsc.Button = _

  def initialize(): Unit = {
    println(s"testCheckBox=$testCheckBox")
    println(s"testButton=$testButton")

    testCheckBox.selected.onChange {
      testButton.text = "changed"
    }
  }
}

When running the application, the println statements show that testCheckBox gets injected properly, but testButton is null. If I click on the checkbox, there is, as expected, a NullPointerException when calling testButton.text_=.

The reason is quite obvious when looking at the compiled classes :

  • There is a TestController$$anonfun$initialize$1 class, for the anonymous function passed to testCheckBox.selected.onChange() in the initialize() method
  • In the TestController class, there are two private fields : testCheckBox (as expected) and test$TestController$$testButton (rather than just testButton), and the accessor/mutator methods. Of those, only the accessor method for test$TestController$$testButton is public.

Clearly, the Scala compiler mangled the name of the testButton field because it had to make its accessor method public (to access it from TestController$$anonfun$initialize$1) and because the field and the accesor/mutator methods should keep the same name.


Now, finally, here is my question: is there a reasonable solution to deal with this situation? Right now, what I have done is make the fields public: since the compiler doesn't need to change their visibility, it won't mangle their name. However, those fields really have no business being public.

Note: Another solution would be to use the scala-fxml library, which completely hides the field injection, but I'd rather use bog-standard FXML loading for other reasons.


Source: (StackOverflow)

Creating custom ScalaFX controls

What exactly is the right way to create a custom ScalaFX control? I'm coming from Swing and Scala Swing, where custom components are simply created by extending Component or Panel. But when I try to extend ScalaFX's Control, I can't extend it without a JavaFX Control delegate. Should I just create custom ScalaFX components by extending the base JavFX classes instead of the ScalaFX classes?


Source: (StackOverflow)

ScalaFX: How to convert an Image object to a byte array

Here below is the code to generate a QR-Code with ScalaFX and ZXing:

import java.util.{HashMap => JavaHashMap}
import org.apache.commons.codec.binary.Base64

import scalafx.scene.image.{Image, PixelFormat, WritableImage}
import scalafx.scene.paint.Color

import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.google.zxing.{BarcodeFormat, EncodeHintType}

object QRCode {

  private val hints = new JavaHashMap[EncodeHintType, Any]() {
    put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L)
  }

  def encode(text: String, size: Int): String = {
    val bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hints)
    val image = toWritableImage(bitMatrix)
    val bytes = // how do I convert image to a byte array?
    Base64.encodeBase64String(bytes)
  }

  private def toWritableImage(bitMatrix: BitMatrix): WritableImage = {
    val image = new WritableImage(bitMatrix.getWidth, bitMatrix.getHeight)
    val writer = image.getPixelWriter
    val format = PixelFormat.getByteRgbInstance
    for (y <- 0 to (bitMatrix.getHeight - 1); x <- 0 to (bitMatrix.getWidth - 1)) {
      writer.setColor(x, y, if (bitMatrix.get(x, y)) Color.Black else Color.White)
    }
    image
  }
}

Since I need the QR-Code as a base64 string, I'm wondering how to convert an Image object to a byte array so that I can convert it to base64 with Apache's commons-codec.


Source: (StackOverflow)

scalafx + intellij : NoClassDefFoundError: javafx/scene/shape/CullFace

I am blocked while trying to create a javafx scala project.I created a scala project in intellij idea 13 (the ast one), then I added manuelly the jar of scalafx ("scalafx_2.10-8.0.0-M1.jar") and copied this little program :

object World extends JFXApp {
stage = new JFXApp.PrimaryStage {
    title = "Hello World"
    width = 600
    height = 450
    scene = new Scene {
        fill = Color.LIGHTGREEN
        content = Set(new Rectangle {
            x = 25
            y = 40
            width = 100
            height = 100
            //fill <== when(hover) then Color.GREEN otherwise Color.RED
        })
    }
}
}

but unfortunately I get this error message:

Exception in Application start method Exception in thread "main" java.lang.RuntimeException: Exception in Application start method at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:399) at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47) at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.NoClassDefFoundError: javafx/scene/shape/CullFace at scalafx.Includes$.(Includes.scala:55)

it seems the problem is linked with javafx, which I ignored since it is normally packed with java7... can you tell me what I done wrong?


Source: (StackOverflow)

ScalaFx: Event Handler with First Class Function

i try to write an event handler in a scalaFx app. I found followin solution:

import scalafx.scene.control.ListView
import javafx.scene.input.MouseEvent
import javafx.event.EventHandler

...

    val list = new ListView[String] {
        onMouseClicked = new EventHandler[MouseEvent] {
            override def handle(event: MouseEvent) {
                doSomething(event)
            }
        }
    }

But this seems to be very Java-style boilerplate code. Is there a way to do this with a first class function like this?

        onMouseClicked = (event: MouseEvent) => doSomething(event)

Compiler says:

No implicit view available from javafx.scene.input.MouseEvent => scalafx.delegate.SFXDelegate[javafx.scene.input.MouseEvent] with javafx.scene.input.MouseEvent.


Source: (StackOverflow)