JXLoginPanel Example

I cannot take credit for all of this work, some of the files in this page were created from skeleton files from the SwingLabs Project. Basically what these classes outlay is a working configuration of JXLoginDialog that authenticates against a table in a mysql database

Class is.ISLoginListener

This class is used to put the last successfull login into preferences so it can be read back and set in the loginPanel next time the user launches

  1. /*
  2. * ISLoginListener.java
  3. *
  4. * Created on 16 November 2005, 14:05
  5. *
  6. * To change this template, choose Tools | Template Manager
  7. * and open the template in the editor.
  8. */
  9.  
  10. package is;
  11. import org.jdesktop.swingx.auth.*;
  12. import org.jdesktop.swingx.JXLoginPanel;
  13.  
  14. /**
  15. *
  16. * @author Greg
  17. */
  18.  
  19. public class ISLoginListener implements LoginListener {
  20.         private JXLoginPanel panel;
  21.         public ISLoginListener(JXLoginPanel panel) {
  22.                 this.panel = panel;
  23.         }
  24.        
  25.         public void loginSucceeded(LoginEvent source) {
  26.                 is.IS_Statics.prefs.putLastLogin(panel.getUserName());
  27.         }
  28.         public void loginStarted(LoginEvent source) {
  29.         }
  30.         public void loginFailed(LoginEvent source) {
  31.         }
  32.         public void loginCanceled(LoginEvent source) {
  33.         }
  34. }

Class is.ISUserNameStore

The user name store is used to keep track of recent logins, providing a drop down box in the panel for users to select the username from.

  1. package is;
  2. import java.beans.PropertyChangeSupport;
  3. import java.util.prefs.Preferences;
  4. import org.jdesktop.swingx.JXLoginPanel;
  5. import org.jdesktop.swingx.auth.UserNameStore;
  6.  
  7. /**
  8. * Saves the user names in Preferences. Because any string could be part
  9. * of the user name, for every user name that must be saved a new Preferences
  10. * key/value pair must be stored.
  11. *
  12. */
  13.  
  14. public class ISUserNameStore extends UserNameStore {
  15.         //The key for one of the preferences
  16.         private static final String USER_KEY = “usernames”;
  17.         private static final String NUM_KEY = “usernames.length”;
  18.  
  19.         /**
  20.         * A name that is used when retrieving preferences. By default, the
  21.         * app name is "default&quot. This should be set by the application
  22.         * if the application wants it’s own list of user names.
  23.         */
  24.         private static final String DEFAULT_APP_NAME = “default”;
  25.        
  26.         /**
  27.         * The preferences node
  28.         */
  29.         private Preferences prefs;
  30.  
  31.         /**
  32.         * Contains the user names. Since the list of user names is not
  33.         * frequently updated, there is no penalty in storing the values
  34.         * in an array.
  35.         */
  36.         private String[] userNames;
  37.  
  38.         /**
  39.         * Used for propogating bean changes
  40.         */
  41.         private PropertyChangeSupport pcs;
  42.  
  43.         /**
  44.         * Creates a new instance of DefaultUserNameStore
  45.         */
  46.        
  47.         public ISUserNameStore() {
  48.                 System.err.println(“Creating”);
  49.                 pcs = new PropertyChangeSupport(this);
  50.                 userNames = new String[0];
  51.                 loadUserNames();
  52.         }
  53.  
  54.         /**
  55.          * Loads the user names from Preferences
  56.         */
  57.         public void loadUserNames() {
  58.                 System.err.println(“Loading usernames”);
  59.                 initPrefs();
  60.                 if (prefs != null) {
  61.                         int n = prefs.getInt(NUM_KEY, 0);
  62.                         String[] names = new String[n];
  63.                         for (int i = 0; i < n; i++) {
  64.                                 names[i] = prefs.get(USER_KEY + “.” + i, null);
  65.                         }
  66.                         setUserNames(names);
  67.                 }
  68.         }
  69.  
  70.         /**
  71.         * Saves the user names to Preferences
  72.         */
  73.         public void saveUserNames() {
  74.                 System.err.println(“Saving Usernames”);
  75.                 initPrefs();
  76.                 if (prefs != null) {
  77.                         prefs.putInt(NUM_KEY, userNames.length);
  78.                         for (int i = 0; i < userNames.length; i++) {
  79.                                 prefs.put(USER_KEY + “.” + i, userNames[i]);
  80.                         }
  81.                 }
  82.         }
  83.  
  84.         /**
  85.         * @inheritDoc
  86.         */
  87.         public String[] getUserNames() {
  88.                 System.err.println(“Get Usernames”);
  89.                 return userNames;
  90.         }
  91.  
  92.         /**
  93.         * @inheritDoc
  94.         */
  95.         public void setUserNames(String[] userNames) {
  96.                 System.err.println(“Setting userNames array”);
  97.                 if (this.userNames != userNames) {
  98.                         String[] old = this.userNames;
  99.                         this.userNames = userNames == null ? new String[0] : userNames;
  100.                         pcs.firePropertyChange(“userNames”, old, this.userNames);
  101.                 }
  102.         }
  103.  
  104.         /**
  105.         * Add a username to the store.
  106.         * @param name
  107.         */
  108.         public void addUserName(String name) {
  109.                 System.err.println(“Adding “+name);
  110.                 if (!containsUserName(name)) {
  111.                         String[] newNames = new String[userNames.length + 1];
  112.                         for (int i=0; i
  113.                                 newNames[i] = userNames[i];
  114.                         }
  115.                         newNames[newNames.length - 1] = name;
  116.                         setUserNames(newNames);
  117.                 }
  118.         }
  119.  
  120.         /**
  121.         * Removes a username from the list.
  122.         *
  123.         * @param name
  124.         */
  125.         public void removeUserName(String name) {
  126.                 System.err.println(“Removing “+name);
  127.                 if (containsUserName(name)) {
  128.                         String[] newNames = new String[userNames.length - 1];
  129.                         int index = 0;
  130.                         for (String s : userNames) {
  131.                                 if (!s.equals(name)) {
  132.                                         newNames[index++] = s;
  133.                                 }
  134.                         }
  135.                         setUserNames(newNames);
  136.                 }
  137.         }
  138.        
  139.         /**
  140.         * @inheritDoc
  141.         */
  142.         public boolean containsUserName(String name) {
  143.                 System.err.println(“Contains “+name);
  144.                 for (String s : userNames) {
  145.                         if (s.equals(name)) {
  146.                                 return true;
  147.                         }
  148.                 }
  149.                 return false;
  150.         }
  151.        
  152.         /**
  153.         * @return Returns Preferences node in which the user names will be stored
  154.         */
  155.         public Preferences getPreferences() {
  156.                 System.err.println(“get prefs”);
  157.                 return prefs;
  158.         }
  159.        
  160.         /**
  161.         * @param prefs the Preferences node to store the user names in. If null,
  162.         * or undefined, then they are stored in /org/jdesktop/swingx/auth/DefaultUserNameStore.
  163.         */
  164.         public void setPreferences(Preferences prefs) {
  165.                 System.err.println(“set prefs”);
  166.                 initPrefs();
  167.                 if (this.prefs != prefs) {
  168.                         Preferences old = this.prefs;
  169.                         this.prefs = prefs;
  170.                         pcs.firePropertyChange(“preferences”, old, prefs);
  171.                         //if prefs is null, this next method will create the default prefs node
  172.                         loadUserNames();
  173.                 }
  174.         }
  175.        
  176.         /**
  177.         * Creates the default prefs node
  178.         */
  179.         private void initPrefs() {
  180.                 System.err.println(“init prefs”);
  181.                 if (prefs == null) {
  182.                         prefs = Preferences.userNodeForPackage(isquote.Main.class);
  183.                         // Use a relative path
  184.                         prefs = Preferences.userRoot().node(“/IS”);
  185.                 }
  186.         }
  187. }

Class: is.ISLoginService

The magic happens here, the LoginService is what authenticates on behalf of the login panel, all you have to do is have the authenticate function return true or false based on whether the login succeeded or failed. Easy huh? As you can see this class is easily adaptable to reading usernames and passwords from anything you want.

  1. package is;
  2. import org.jdesktop.swingx.auth.LoginService;
  3. import org.jdesktop.swingworker.SwingWorker;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.util.Properties;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import java.sql.Connection;
  10. import java.sql.Statement;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13.  
  14. /**
  15. * A login service for authenticating against a SQL Table using JDBC
  16. *
  17. * @author Greg Tangey
  18. */
  19. public class ISLoginService extends LoginService {
  20.         private static final Logger LOG = Logger.getLogger(ISLoginService.class.getName());
  21.         private Connection con;
  22.        
  23.         /**
  24.         * Creates a new LoginService and initializses it to connect.
  25.         */
  26.         public ISLoginService() {
  27.                 System.out.println(“Created service”);
  28.         }
  29.         public Connection getConnection() {
  30.                 return con;
  31.         }
  32.        
  33.         /**
  34.         * @param name    user name
  35.         * @param password    user password
  36.         * @param server Must be either a valid JDBC URL for the type of JDBC driver you are using,
  37.         * or must be a valid JNDIContext from which to get the database connection
  38.         */
  39.         public boolean authenticate(final String username, char[] pass, String server) throws Exception {
  40.                 String password = new String(pass);
  41.                 final String md5password = is.MD5Hash.hash(password);
  42.                 final String latestVersion;
  43.                 String dbPassword = “”;
  44.                 Exception e;
  45.                 try {
  46.                         con = is.IS_Statics.ISPool.getConnection();
  47.                         if (con != null) {
  48.                                 Statement s = con.createStatement();
  49.                                 ResultSet rs = s.executeQuery( “SELECT user_id,passphrase,access_level,homebin FROM users where `login` = \” + username + \”);
  50.                                 while (rs.next()) {
  51.                                         is.IS_Statics.userID = (rs.getInt (“user_id”));
  52.                                         is.IS_Statics.userLevel = (rs.getInt (“access_level”));
  53.                                         is.IS_Statics.userName = username;
  54.                                         dbPassword = (rs.getString(“passphrase”));
  55.                                 }
  56.                                 rs.close();
  57.                         }
  58.                         else {
  59.                                 System.err.println(“Connection NULL return false”);
  60.                                 return false;
  61.                         }
  62.                 }
  63.                 catch (SQLException e2) {
  64.                         System.err.println(e2.toString());
  65.                         System.out.println(“Exception caught return false”);
  66.                         return false;
  67.                 }
  68.                 finally {
  69.                         try {
  70.                                 con.close();
  71.                         }
  72.                         catch(SQLException e3) {
  73.                                 System.err.println(e3.toString());
  74.                         }
  75.                 }
  76.                 if (md5password.equals(dbPassword) == true) {
  77.                         is.IS_Statics.prefs.putLastLogin(username);
  78.                         // clear the login/password from the dialog
  79.                         setupApp();
  80.                         System.out.println(“Password correct return true”);
  81.                         return true;
  82.                 }
  83.                 else {
  84.                         System.out.println(“Password incorrect return false”);
  85.                         return false;
  86.                 }
  87.         }
  88.  
  89.         private void setupApp() {
  90.         /* I use this to get any kind of data from the database that doesnt change much and
  91.         * is used frequently */
  92.         }
  93. }

How to initiate and display:

Below is how we initiate the LoginPanel with all its various extras and then show it as a modal dialog blocking a frame

  1. // Create a new login service for use with the JXLoginPanel
  2. is.ISLoginService service = new is.ISLoginService();
  3. // Create new JXLoginPanel to use with the Diaog
  4. is.IS_Statics.loginPanel = new JXLoginPanel(service, null, new is.ISUserNameStore(), null);
  5. // Add Login listerner to the login service to handle placing the last login
  6. // in preferences after the login is successfull
  7. service.addLoginListener(new is.ISLoginListener(is.IS_Statics.loginPanel));
  8. // Set the last successfull logins username from preferences
  9. is.IS_Statics.loginPanel.setUserName(is.IS_Statics.prefs.getLastLogin());
  10. // Show login dialog modal, blocking the mainFrame
  11. // is.IS_Statics.mainFrame is thea Frame you want to the modal login dialog to block
  12. // is.IS_Statics.loginPanel is the loginPanel we just created
  13. org.jdesktop.swingx.JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(is.IS_Statics.mainFrame,is.IS_Statics.loginPanel);
  14. // If close button is pressed, or X on the dialog window, quit the app
  15. if(status == JXLoginPanel.Status.CANCELLED || status == JXLoginPanel.Status.NOT_STARTED) {
  16.         is.IS_Statics.mainFrame.dispose();
  17. }

One Response to “JXLoginPanel Example”

  1. LuizLuiz


    very good article!