3

I just started learning Scala, and as part of the process, I've been trying to write some simple scripts that use Swing.

Here is an extremely stripped down example which exhibits the problem that I am seeing.

SimpleSwingApp:

import scala.swing._
object SimpleSwingApp extends SimpleSwingApplication {
  def top = new MainFrame {
    println ("Starting")
    title = "First Swing App"
    contents = new Button { text = "Click me" }
  }
}

When I run the script through the Eclipse Scala IDE as a Scala Application, everything works as expected. I get the expected "Starting" text printed to the Eclipse console and the little GUI pops up and waits for a click.

When I try to run it as a script from the command line, I get nothing.

> scala SimpleSwingApp.scala

No error message, no "Starting", no GUI.

So what is going on, and how can I achieve the result that I want (ie, starting a Scala GUI script from the command line)?

2 Answers 2

4

The problem is that the Scala script runner is looking for a main method in your script file, but it isn't finding one.

The reason it isn't finding one is because you are inheriting main from SimpleSwingApplication, so there isn't a main method in your script file.

You can work around the problem by adding a main method to your script that immediately invokes super.main, as follows:

import scala.swing._
object SimpleSwingApp extends SimpleSwingApplication {

  override def main(args: Array[String]) = super.main(args)

  def top = new MainFrame {
    println("Starting")
    title = "First Swing App"
    contents = new Button { text = "Click me" }
  }
}

Now, the script will not raise an error in the Scala IDE, and it can be executed by calling

scala SimpleSwingApp.scala 

rather than the less aesthetic

scala -i SimpleSwingApp.scala -e "SimpleSwingApp.main(args)"
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to run it from the command line, add an explicit call to main at the bottom of the file:

SimpleSwingApp.main(Array())

If you compile this with scalac first, then run, it will work without explicitly calling main.

1 Comment

Thanks for you answer. That does indeed work. Unfortunately, it raises an error in the Scala IDE for Eclipse. Finding the solution to that lead me to this answer, which solves the IDE error. Essentially, if I call my script with scala -i SimpleSwingApp.scala -e "SimpleSwingApp.main(args)" it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.