Thursday, May 31, 2012

JavaFX 2: Create Nice Login Form

In this JavaFX tutorial I will design a nice looking Login Form with JavaFX 2 and CSS. It's clasic login form with username and password, and login button. In order to follow this tutorial I strongly recommend you to check these tutorials below:
-->
Username: JavaFX2
Password: password

You can enter this information above and click on Login button. It will tell you with a little message that login is successful, but if you enter wrong information, it will tell you with a little message that login isn't successful.

The final output screenshot of this tutorial will be like below image.
JavaFX 2 Login Form
JavaFX 2 Login Form
Here is Java code of our example:
 
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. import javafx.application.Application;
  2. import javafx.event.ActionEvent;
  3. import javafx.event.EventHandler;
  4. import javafx.geometry.Insets;
  5. import javafx.scene.Scene;
  6. import javafx.scene.control.Button;
  7. import javafx.scene.control.Label;
  8. import javafx.scene.control.PasswordField;
  9. import javafx.scene.control.TextField;
  10. import javafx.scene.effect.DropShadow;
  11. import javafx.scene.effect.Reflection;
  12. import javafx.scene.layout.BorderPane;
  13. import javafx.scene.layout.GridPane;
  14. import javafx.scene.layout.HBox;
  15. import javafx.scene.paint.Color;
  16. import javafx.scene.text.Font;
  17. import javafx.scene.text.FontWeight;
  18. import javafx.scene.text.Text;
  19. import javafx.stage.Stage;
  20.  
  21. /**
  22.  *
  23.  * @web http://zoranpavlovic.blogspot.com/
  24.  */
  25. public class Login extends Application {
  26.  
  27.     String user = "JavaFX2";
  28.     String pw = "password";
  29.     String checkUser, checkPw;
  30.    
  31.     public static void main(String[] args) {
  32.         launch(args);
  33.     }
  34.      
  35.     @Override
  36.     public void start(Stage primaryStage) {
  37.         primaryStage.setTitle("JavaFX 2 Login");
  38.        
  39.         BorderPane bp = new BorderPane();
  40.         bp.setPadding(new Insets(10,50,50,50));
  41.        
  42.         //Adding HBox
  43.         HBox hb = new HBox();
  44.         hb.setPadding(new Insets(20,20,20,30));
  45.        
  46.         //Adding GridPane
  47.         GridPane gridPane = new GridPane();
  48.         gridPane.setPadding(new Insets(20,20,20,20));
  49.         gridPane.setHgap(5);
  50.         gridPane.setVgap(5);
  51.        
  52.        //Implementing Nodes for GridPane
  53.         Label lblUserName = new Label("Username");
  54.         final TextField txtUserName = new TextField();
  55.         Label lblPassword = new Label("Password");
  56.         final PasswordField pf = new PasswordField();
  57.         Button btnLogin = new Button("Login");
  58.         final Label lblMessage = new Label();
  59.        
  60.         //Adding Nodes to GridPane layout
  61.         gridPane.add(lblUserName, 0, 0);
  62.         gridPane.add(txtUserName, 1, 0);
  63.         gridPane.add(lblPassword, 0, 1);
  64.         gridPane.add(pf, 1, 1);
  65.         gridPane.add(btnLogin, 2, 1);
  66.         gridPane.add(lblMessage, 1, 2);
  67.        
  68.                
  69.         //Reflection for gridPane
  70.         Reflection r = new Reflection();
  71.         r.setFraction(0.7f);
  72.         gridPane.setEffect(r);
  73.        
  74.         //DropShadow effect
  75.         DropShadow dropShadow = new DropShadow();
  76.         dropShadow.setOffsetX(5);
  77.         dropShadow.setOffsetY(5);
  78.        
  79.         //Adding text and DropShadow effect to it
  80.         Text text = new Text("JavaFX 2 Login");
  81.         text.setFont(Font.font("Courier New", FontWeight.BOLD, 28));
  82.         text.setEffect(dropShadow);
  83.        
  84.         //Adding text to HBox
  85.         hb.getChildren().add(text);
  86.                          
  87.         //Add ID's to Nodes
  88.         bp.setId("bp");
  89.         gridPane.setId("root");
  90.         btnLogin.setId("btnLogin");
  91.         text.setId("text");
  92.                
  93.         //Action for btnLogin
  94.         btnLogin.setOnAction(new EventHandler<ActionEvent>() {
  95.             public void handle(ActionEvent event) {
  96.                 checkUser = txtUserName.getText().toString();
  97.                 checkPw = pf.getText().toString();
  98.                 if(checkUser.equals(user) && checkPw.equals(pw)){
  99.                     lblMessage.setText("Congratulations!");
  100.                     lblMessage.setTextFill(Color.GREEN);
  101.                 }
  102.                 else{
  103.                     lblMessage.setText("Incorrect user or pw.");
  104.                     lblMessage.setTextFill(Color.RED);
  105.                 }
  106.                 txtUserName.setText("");
  107.                 pf.setText("");
  108.             }
  109.             });
  110.        
  111.         //Add HBox and GridPane layout to BorderPane Layout
  112.         bp.setTop(hb);
  113.         bp.setCenter(gridPane);  
  114.        
  115.         //Adding BorderPane to the scene and loading CSS
  116.         Scene scene = new Scene(bp);
  117.         scene.getStylesheets().add(getClass().getClassLoader().getResource("login.css").toExternalForm());
  118.         primaryStage.setScene(scene);
  119.           primaryStage.titleProperty().bind(
  120.                     scene.widthProperty().asString().
  121.                     concat(" : ").
  122.                     concat(scene.heightProperty().asString()));
  123.         //primaryStage.setResizable(false);
  124.         primaryStage.show();
  125.     }
  126. }

In order to style this application properly you'll need to create login.css file in /src folder of your project.
If you dont know how to do that, please check out JavaFX 2: Styling Buttons tutorial.
.
--> Here is CSS code of our example:
 
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #root {
  2.     -fx-background-color:  linear-gradient(lightgray, gray);
  3.     -fx-border-color: white;
  4.     -fx-border-radius: 20;
  5.     -fx-padding: 10 10 10 10;
  6.     -fx-background-radius: 20;
  7.    
  8. }
  9.  
  10. #bp {
  11.     -fx-background-color:  linear-gradient(gray,DimGrey );
  12.    
  13. }
  14.  
  15. #btnLogin {
  16.     -fx-background-radius: 30, 30, 29, 28;
  17.     -fx-padding: 3px 10px 3px 10px;
  18.     -fx-background-color:   linear-gradient(orange, orangered );
  19. }
  20.  
  21. #text {
  22.     -fx-fill:  linear-gradient(orange , orangered);
  23. }

Thats'all folks for this tutorial, if you have any comments or problems, feel free to comment. If you like this tutorial, you can check out more JavFX 2 tutorials on this blog.

You might want to take a look at these tutorials below:



31 comments:

  1. Great! I've been looking for some cool JavaFX login form today! :)

    ReplyDelete
  2. I hope that this tutorial will help you. If you have some problems with creating login form, let me know by leaving a comment.

    Feel free to share tutorial, and to check some other JavaFX tutorials on this blog.

    ReplyDelete
  3. hi, line 117, the shorter version works fine for me,

    scene.getStylesheets().add("login.css");

    ReplyDelete
  4. Cool, I tried the same, but I failed.

    ReplyDelete
  5. I used JDK 7U5 with FX 2.1 SDK and e(fx)clipse,

    ReplyDelete
  6. Thanks for the info, I must try e(fx)clipse.

    ReplyDelete
  7. Hi,

    In the current version of JavaFX2 (2.1) loading the css with the getClass() does not work. If you replace it by the actual name of the class it does.

    So loading the login.css works if you code it like this:

    scene.getStylesheets().add(Login.getClassLoader().getResource("login.css").toExternalForm());

    ReplyDelete
  8. I didn't know that. Thank you. ;)

    ReplyDelete
  9. When I try to call a program written in java using java 7 U 5 which initiates jFileChooser, the login program hangs. I've tried to debug it, seems like a I might have hit a dead end.

    if(sa.SearchByName(checkUser,checkPw,checkSk)){
    //lblMessage.setText("Congratulations!");
    //lblMessage.setTextFill(Color.GREEN);
    //lblMessage1.setText("Please Proceed.");
    //lblMessage1.setTextFill(Color.GREEN);
    System.out.println("Confirmed");
    proceed = true;
    if(proceed == true){
    System.out.println("I am in finally block");
    FileGUI fg = new FileGUI();

    try {
    fg.Callmain();
    System.out.println("Success");
    } catch (NullPointerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }System.exit(0);
    }

    ReplyDelete
  10. figured it out seems the Stage needs to be closed before calling jfilechooser class

    ReplyDelete
  11. hi , can you please tell me how to navigate to another window ( scene ) by clicking the button login?

    ReplyDelete
  12. Ofc :)

    http://zoranpavlovic.blogspot.com/2012/06/javafx-2-create-dialog-with-stage.html

    ReplyDelete
  13. Great code.....
    Java use css in client based application thats great...

    ReplyDelete
  14. Assuming CSS and Class are in the same package : scene.getStylesheets().add(getClass().getResource("login.css").toString());

    ReplyDelete
  15. Amusing. user Interface like web version in Client based Application

    ReplyDelete
  16. Ketofirm Forskolin Reviews Have a table for eating only. This is important because you will only be able to eat in this certain area of your home. Make it either the kitchen or the dining room, and don't allow yourself to snack anywhere else. This will help you to also understand when you are truly hungry for a meal, or if you just want to snack while watching TV.

    https://fitose.com/ketofirm-forskolin/

    ReplyDelete
  17. Keto Slim 7 Reviews The approach followed by the program is a well-structured one. Often people wonder as to how the weight loss factor program work. It should be known by them that the program is for 12 weeks approximately and can be undertaken again after 12 weeks are over if the results are not satisfactory. The said program begins with a detoxing phase initially that cleans the toxins from the body and makes the process of shedding weight faster.

    https://fitose.com/keto-slim-7/

    ReplyDelete
  18. IBX Male Enhancement But according to some clinical studies conducted on natural male enhancements, products using natural herb extracts are also equally effective, but there are less side effects and health risks involved when taking synthetic pills or undergoing surgical procedures in order to increase the penile size. The good thing about all natural male enhancement products is that these are made from natural herbal extracts that not only have an effect on the penile size but on the general health as well.

    https://fitose.com/ibx-male-enhancement/

    ReplyDelete
  19. But what does this mean? For some, this can make pleasurable moments more exciting and satisfying. Gaining a bigger size can introduce a whole new level of intimacy as it can also introduce new sensations to partners. Horsepower Plus Some see it as a solution for their marital problems, while others consider it as the best way to boost their self-esteem.

    ReplyDelete
  20. Where age is not a factor, a younger man with sexual dysfunction may be psychological in origin. Staminon Reviews SymptomsHow to Cure Premature Ejaculation Major erectile dysfunction symptoms are lack of desire, difficulty achieving erection, diminishing erection before completion and partial erections.

    ReplyDelete
  21. Ginseng: Studies have proved that Korean red ginseng is very much powerful to stimulate the function of male reproductive organs. It has the efficiency to stop the symptoms of ED, but it is necessary in taking the advice of a health expert, Male Ultracore Reviews because this herb may arise allergic reactions. Ginseng is considered as one of the best herbal remedies to prevent and treat ED completely.

    ReplyDelete