如何从console main方法运行SimpleSwingApplication?

时间:2011-10-26 18:19:33

标签: swing scala console

我在Scala中编写了我的第一个控制台应用程序,并且我在Scala中编写了我的第一个Swing应用程序 - 如果是后者,我的对象中的入口点是顶部方法,扩展了 SimpleSwingApplication

但是,我仍然希望通过方法,并从那里调用顶部 - 或执行其他等效操作(如创建窗口并“运行”它)。

怎么做?

万一你好奇为什么,GUI是可选的,所以我想解析命令行参数,然后决定显示(或不显示)应用程序窗口。

4 个答案:

答案 0 :(得分:4)

如果你有类似的话:

object MySimpleApp extends SimpleSwingApplication {
  // ...
}

您只需致电MySimpleApp.main即可从控制台启动它。混合main特征时会添加SimpleSwingApplication方法。看看scaladoc

答案 1 :(得分:4)

这是最基本的例子:

import swing._

object MainApplication {
  def main(args: Array[String]) = {
    GUI.main(args)
 }

  object GUI extends SimpleSwingApplication {
    def top = new MainFrame {
      title = "Hello, World!"
    }
  }
}

从命令行执行scala MainApplication.scala以启动Swing应用程序。

答案 2 :(得分:2)

如果覆盖从SimpleSwingApplication继承的main方法,则可以执行任何操作:

object ApplicationWithOptionalGUI extends SimpleSwingApplication {

  override def main(args: Array[String]) =
    if (parseCommandLine(args))
      super.main(args) // Starts GUI
    else
      runWithoutGUI(args)

...

}

答案 3 :(得分:0)

我需要main.args在SimpleSwingApplication中可用。我想提供一个文件名作为CLI中的参数进行处理,或者在命令行参数列表为空的情况下使用JFileChooser。

我不知道在SimpleSwingApplication中是否有使用命令行参数的简单方法,但是我如何工作的是在demoapp.class中进行定义:

class demoSSA(args: Array[String]) extends SimpleSwingApplication {
    ....
    var filename: String = null
    if (args.length > 0) {
        filename = args(0)
    } else {
        // use JFileChooser to select filename to be processed 
        // https://stackoverflow.com/questions/23627894/scala-class-running-a-file-chooser
    }
    ....
}

object demo {
  def main(args: Array[String]): Unit = {
     val demo = new demoSSA(args)
     demo.startup(args)
  }
}

然后通过以下方式启动应用 demo [args] ,通过将filename用作CLI参数或将其保留为空,然后程序使用JFileChooser进行询问。

是否有办法在SimpleSwingApplication单例对象中获取main()的参数? 因为解析覆盖的SimpleSwingApplication.main中的“文件名”并在单例对象中使用“文件名”不起作用,因此需要声明它(val args:Array [String] = null;),而不仅仅是声明(val args) :Array [String];)。从SSA继承的单例objecs不能具有参数。

(编辑) 找到了另一种方法: 如果将整个demoSSA放在重写的main()或startup()内部,则top MainFrame需要在外部定义为top = null,然后从startup()声明为this.top:

object demo extends SimpleSwingApplication {  
  var top: MainFrame = null
  override def startup(args: Array[String]) {
    ...  // can use args here
    this.top = new MainFrame {
      ... // can use args here also
    };
    val t = this.top
    if (t.size == new Dimension(0,0)) t.pack()
      t.visible = true
  }
}

但是我想我更喜欢前一种方法,它具有分离的主要对象。它比后一种方法至少少一个层次缩进。