问题
Im trying to create an login window for an app im doing. I have searched all day for an example but I cant seem to find anything that helps. My basic structure is as follows:
// App.scala
object App extends SimpleSwingApplication {
val ui = new BorderPanel {
//content
}
def top = new MainFrame {
title = "title"
contents = ui
}
}
So whats the strategy to create a login box without the mainframe showing and closing it after login and displaying the mainframe. thanks
回答1:
Here is working example. Took it from one of my projects and adjusted a little bit for you:
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()
}
As you can see I'm generally using modal dialog, so it will block during application initialization. There 2 outcomes: either user makes successful login and sees your main frame or he closes login dialog and IllegalStateException
would be thrown.
来源:https://stackoverflow.com/questions/7921182/scala-swing-newbie