Pages

How to use JCalendar date picker in your Java Swing Applications with NetBeans

How to use JCalendar date picker in your Java Swing Applications with NetBeans


If you are one of those JAVA beginners like me who wants to implement a datepicker module in your experimental/business critical application developed with NetBeans IDE , then this for you. Let me share how I figured out to do so in simple steps with a sample code.
  1. Assuming that you have your Java Swing application ready, you will need to download the JCalendar package from herehttp://www.toedter.com/en/jcalendar/index.html . The page lists out various modules available with descriptions like JDateChooser, JCalendar, JYearChooser, JMonthChooser, JDayChooser, JSpinField and JLocaleChooser. The one I chose for my app was JDateChooser.
  2. After downloading and opening the ZIP file, you can see a whole set of files in it. The one we need is in the folder ‘lib’ with the name jcalendar-1.4.jar (this is the latest version while I was writing this). extract that file to your folder of comfort.

    JCalendar zip file
  3. The jar file you just extracted contains everything you need to implement the date picker in your Java Swing application. It requires few simple manoeuvres. Go to NetBeans, From Tools menu select Libraries. The Library Manager window will be displayed with list of existing libraries that makes built-in readymade functionality ready at our disposal.

    NetBeans Library
  4. Now our need is to create a new library for JCalendar. By now its obvious, so click on New Library… button. A new window will open requiring us to enter a name for the new library. I name mine as ‘JCalendar’.

    New Library NetBeans
  5. Next step is to import the extracted jcalendar-1.4.jar file in to the library. Click onAdd JAR/Folder… button on the right-side pane of Library Manager window. Import the extracted jcalendar-1.4.jar file. One imported it would look something like in the below screenprint. Click OK and close the Library Manager. We are done with Library Manager here. Note that what we are done here is creating a new library for JCalendar. You need to separately make this library available to each of your projects whenever needed. I will come to this point in upcoming steps.

    Add JAR to Library Netbeans
  6. Now that you have JCalendar library , the next step is to include the JCalendar modules in your Swing Palette. The default Swing Palette available in NetBeans looks like the one below.

    Swing Palette in NetBeans
    From Tools menu select Palette > Swing/AWT Components . This will openPalette Manger Window that provides a way to organize default drag and drop modules available as we talked about in previous point.
  7. I prefer to create a new category for adding JCalendar modules in to palette. So click on New Category . I named mine as ‘Third Party Components’.

    Third Party Components NetBeans Swing Palette
  8. Now click on Add from Library… button to select the Jcalendar library that we created already.

    Install Components to Palette NetBeans
  9. On clicking Next it will display the set of available modules from JCalendar library to choose from, that can be added in the palette. This is a multiselection window, so you can choose any component you need. I wanted to have JDateChooser in my application so I select it.

    JDateChooser NetBeans
  10. On clicking Next again you will be provided with options to categorize the newly imported components. As promised I’m going to import it in to the ‘Third Party Components' category. click Finish . click Close . Done!!! we will now have JDateChooser as a drag and drop module in NetBeans Swing palette like any other Swing component.
    .
    Category NetBeans
  11. Now we have JCalendar library and palette, but I have a feeling that we are still missing something. Yes by default these libraries wont be available in each projects we create. Its like summoning beauticians, electricians, carpenters, geologists to perform a surgery. All we need is a Surgeon. So for each of our projects we need to import these specific required libraries individually. So now I’m going to import the library in to my project. To do so right-click on the project you are working on and select Properties.

    Project Properties NetBeans
  12. In Project Properties Window, under Categories go to Libraries. Click on Add Library . Select the JCalendar library we created. Click Add Library. Click OK. Now we are all set. Let me show You a sample code to deal with the JCalendar.
Class with Main Method:
   1: /*
   2:  * To change this template, choose Tools | Templates
   3:  * and open the template in the editor.
   4:  */
   5: package calendar.app;
   6:  
   7: /**
   8:  *
   9:  * @author greenxgene
  10:  */
  11: public class CalendarApp {
  12:  
  13:     /**
  14:      * @param args the command line arguments
  15:      */
  16:     public static void main(String[] args) {
  17:         DatePickerExample dpe = new DatePickerExample();
  18:         dpe.setVisible(true);
  19:     }
  20: }

JFrame Class with Swing Componnets: (Refer to Line 112 to 116)





   1: /*
   2:  * To change this template, choose Tools | Templates
   3:  * and open the template in the editor.
   4:  */
   5: package calendar.app;
   6:  
   7: import java.util.Calendar;
   8:  
   9: /**
  10:  *
  11:  * @author greenxgene
  12:  */
  13: public class DatePickerExample extends javax.swing.JFrame {
  14:  
  15:     /**
  16:      * Creates new form DatePickerExample
  17:      */
  18:     public DatePickerExample() {
  19:         initComponents();
  20:     }
  21:  
  22:     /**
  23:      * This method is called from within the constructor to initialize the form.
  24:      * WARNING: Do NOT modify this code. The content of this method is always
  25:      * regenerated by the Form Editor.
  26:      */
  27:     @SuppressWarnings("unchecked")
  28:     // <editor-fold defaultstate="collapsed" desc="Generated Code">
  29:     private void initComponents() {
  30:  
  31:         jPanel1 = new javax.swing.JPanel();
  32:         outputtextbox = new javax.swing.JTextField();
  33:         mydatechooser = new com.toedter.calendar.JDateChooser();
  34:         jLabel1 = new javax.swing.JLabel();
  35:         jLabel2 = new javax.swing.JLabel();
  36:         jButton1 = new javax.swing.JButton();
  37:  
  38:         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  39:         setTitle("Date Picker Example");
  40:  
  41:         jLabel1.setText("Choose Date");
  42:  
  43:         jLabel2.setText("Output");
  44:  
  45:         jButton1.setText("Get Date");
  46:         jButton1.addActionListener(new java.awt.event.ActionListener() {
  47:             public void actionPerformed(java.awt.event.ActionEvent evt) {
  48:                 jButton1ActionPerformed(evt);
  49:             }
  50:         });
  51:  
  52:         javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
  53:         jPanel1.setLayout(jPanel1Layout);
  54:         jPanel1Layout.setHorizontalGroup(
  55:             jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  56:             .addGroup(jPanel1Layout.createSequentialGroup()
  57:                 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  58:                     .addGroup(jPanel1Layout.createSequentialGroup()
  59:                         .addGap(147, 147, 147)
  60:                         .addComponent(jLabel1))
  61:                     .addGroup(jPanel1Layout.createSequentialGroup()
  62:                         .addGap(143, 143, 143)
  63:                         .addComponent(jButton1))
  64:                     .addGroup(jPanel1Layout.createSequentialGroup()
  65:                         .addGap(165, 165, 165)
  66:                         .addComponent(jLabel2))
  67:                     .addGroup(jPanel1Layout.createSequentialGroup()
  68:                         .addGap(123, 123, 123)
  69:                         .addComponent(mydatechooser, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
  70:                     .addGroup(jPanel1Layout.createSequentialGroup()
  71:                         .addGap(65, 65, 65)
  72:                         .addComponent(outputtextbox, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)))
  73:                 .addContainerGap(83, Short.MAX_VALUE))
  74:         );
  75:         jPanel1Layout.setVerticalGroup(
  76:             jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  77:             .addGroup(jPanel1Layout.createSequentialGroup()
  78:                 .addContainerGap()
  79:                 .addComponent(jLabel1)
  80:                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  81:                 .addComponent(mydatechooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  82:                 .addGap(13, 13, 13)
  83:                 .addComponent(jButton1)
  84:                 .addGap(25, 25, 25)
  85:                 .addComponent(jLabel2)
  86:                 .addGap(18, 18, 18)
  87:                 .addComponent(outputtextbox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  88:                 .addContainerGap(25, Short.MAX_VALUE))
  89:         );
  90:  
  91:         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  92:         getContentPane().setLayout(layout);
  93:         layout.setHorizontalGroup(
  94:             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  95:             .addGroup(layout.createSequentialGroup()
  96:                 .addContainerGap()
  97:                 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  98:                 .addContainerGap())
  99:         );
 100:         layout.setVerticalGroup(
 101:             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
 102:             .addGroup(layout.createSequentialGroup()
 103:                 .addContainerGap()
 104:                 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
 105:                 .addContainerGap())
 106:         );
 107:  
 108:         pack();
 109:     }// </editor-fold>
 110:  
 111:     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
 112:         Calendar cal = mydatechooser.getCalendar();
 113:         int datevar = cal.get(Calendar.DATE);
 114:         int monthvar = cal.get(Calendar.MONTH);
 115:         int yearvar = cal.get(Calendar.YEAR);
 116:         outputtextbox.setText("Date is " + datevar + ", Month is " + monthvar + " and Year is "+ yearvar + ".");
 117:         
 118:     }
 119:  
 120:     /**
 121:      * @param args the command line arguments
 122:      */
 123:     public static void main(String args[]) {
 124:         /*
 125:          * Set the Nimbus look and feel
 126:          */
 127:         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
 128:         /*
 129:          * If Nimbus (introduced in Java SE 6) is not available, stay with the
 130:          * default look and feel. For details see
 131:          * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
 132:          */
 133:         try {
 134:             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
 135:                 if ("Nimbus".equals(info.getName())) {
 136:                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
 137:                     break;
 138:                 }
 139:             }
 140:         } catch (ClassNotFoundException ex) {
 141:             java.util.logging.Logger.getLogger(DatePickerExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 142:         } catch (InstantiationException ex) {
 143:             java.util.logging.Logger.getLogger(DatePickerExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 144:         } catch (IllegalAccessException ex) {
 145:             java.util.logging.Logger.getLogger(DatePickerExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 146:         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
 147:             java.util.logging.Logger.getLogger(DatePickerExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
 148:         }
 149:         //</editor-fold>
 150:  
 151:         /*
 152:          * Create and display the form
 153:          */
 154:         java.awt.EventQueue.invokeLater(new Runnable() {
 155:  
 156:             public void run() {
 157:                 new DatePickerExample().setVisible(true);
 158:             }
 159:         });
 160:     }
 161:     // Variables declaration - do not modify
 162:     private javax.swing.JButton jButton1;
 163:     private javax.swing.JLabel jLabel1;
 164:     private javax.swing.JLabel jLabel2;
 165:     private javax.swing.JPanel jPanel1;
 166:     private com.toedter.calendar.JDateChooser mydatechooser;
 167:     private javax.swing.JTextField outputtextbox;
 168:     // End of variables declaration
 169: }

Note : When you compile and build the code you will your application jar file along with a lib folder that contains supporting JCalendar file without which the application will not run. So dont tamper with it.

I will be more than glad to receive your comments and queries

1 comment:

  1. However, when we create a Jar file for the entire project and run it on a Mac, it does not work . For some reason it does not connect to the external dependencies like JCalendar.jar. No issues on Windows. Any help or solution?

    ReplyDelete