Scala Swing新手

Ray*_*win 3 scala scala-swing

我正在尝试为应用程序创建一个登录窗口.我整天都在寻找一个例子,但我似乎无法找到任何有用的东西.我的基本结构如下:

// App.scala
object App extends SimpleSwingApplication {
  val ui = new BorderPanel {
    //content
  }

  def top = new MainFrame {
    title = "title"
    contents = ui
  }
}
Run Code Online (Sandbox Code Playgroud)

那么,在登录和显示大型机之后,创建一个没有大型机显示和关闭它的登录框的策略是什么.谢谢

ten*_*shi 6

这是一个有效的例子.从我的一个项目中取出它并为你调整一下:

import swing._
import scala.swing.BorderPanel.Position._

object App extends SimpleSwingApplication {
  val ui = new BorderPanel {
    //content
  }

  def top = new MainFrame {
    title = "title"
    contents = ui
  }

  val auth = new LoginDialog().auth.getOrElse(throw new IllegalStateException("You should login!!!"))
}

case class Auth(userName: String, password: String)

class LoginDialog extends Dialog {
  var auth: Option[Auth] = None
  val userName = new TextField
  val password = new PasswordField

  title = "Login"
  modal = true

  contents = new BorderPanel {
    layout(new BoxPanel(Orientation.Vertical) {
      border = Swing.EmptyBorder(5,5,5,5)

      contents += new Label("User Name:")
      contents += userName
      contents += new Label("Password:")
      contents += password
    }) = Center

    layout(new FlowPanel(FlowPanel.Alignment.Right)(
      Button("Login") {
        if (makeLogin()) {
          auth = Some(Auth(userName.text, password.text))
          close()
        } else {
          Dialog.showMessage(this, "Wrong username or password!", "Login Error", Dialog.Message.Error)
        }
      }
    )) = South
  }

  def makeLogin() = true // here comes you login logic

  centerOnScreen()
  open()
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我通常使用模态对话框,因此它会在应用程序初始化期间阻塞.有2个结果:用户成功登录并看到您的主框架或他关闭登录对话框IllegalStateException并将被抛出.