Skip to main content

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 here http://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 on Add 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 open Palette 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.

If you find this article useful you are free donate to keep me going.

Here is my Bitcoin wallet address

1PGXWmomcG3dNMrt636UBR2s6SVHtS75U8

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

Comments

  1. could u please tell me how to add JCalendar in gwt applications using eclipse...please give me reply soon its urgent in my application .

    ReplyDelete
    Replies
    1. Sorry I dont know the answer yet for your query as I'm not familiar with GWT.

      Delete
  2. hi all,
    i am new to java programing...
    i have used jDateChooser and i want to extract just month i.e. int value of selected month or date i.e. int value of selected date from jDateChooser......?
    Eg. if choose date as 2012/11/07
    I want all in separate like

    Year = 2012
    Month = 11
    Date = 07

    how do i do that in java...???

    ReplyDelete
    Replies
    1. Hi Karan, I have included the source code for that. Anyway here is the snippet for your reference.

      private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

      Calendar cal = mydatechooser.getCalendar();
      int datevar = cal.get(Calendar.DATE);
      int monthvar = cal.get(Calendar.MONTH);
      int yearvar = cal.get(Calendar.YEAR);
      // other operations with your date

      }

      Delete
  3. I have a problem, if I want to make a new CellEditor for the JTable, I write:

    TableCellEditor jDateEditor = new DefaultCellEditor(com.toedter.calendar.JDateChooserCellEditor);

    but than the error "package com.toedter does not exist" appears.
    do you know how to use this package as a cell editor?
    In the project libraries the JCalendar exists, how can I now use this library?

    ReplyDelete
    Replies
    1. ok I solved the problem:

      private com.toedter.calendar.JDateChooserCellEditor jDateEditor = new com.toedter.calendar.JDateChooserCellEditor();

      jTable.getColumn("Date").setCellRenderer(DateRenderer);

      Delete
    2. ok Sam. Anyway you can use a import statement at the beginning of the Class like this.

      import com.toedter.calendar.JDateChooserCellEditor;

      Delete
  4. Is there anyway to display the month in word, like month = january.

    ReplyDelete
    Replies
    1. Yes Zack it possible

      Calendar cal = mydatechooser.getCalendar();

      Date da = new Date(cal.getTimeInMillis());

      String monthname = new SimpleDateFormat("MMMM").format(da);

      // The string monthname gives you month in full format. eg. November

      String monthname = new SimpleDateFormat("MMM").format(da);

      // The string monthname gives you month in short format. eg. Nov


      You need to include the below import statements

      import java.text.SimpleDateFormat;
      import java.util.Calendar;
      import java.util.Date;

      Delete
    2. Thank you. There is another question, how if i want to display different month in one time? example like i want to display march & may?

      Delete
    3. Just simple arithmetics.

      Calendar cal = mydatechooser.getCalendar();
      Date da1 = new Date(cal.getTimeInMillis());
      String monthname1 = new SimpleDateFormat("MMMM").format(da1);

      //increment the month from todays date. Here for instance, increment by 2 months.
      cal.add(Calendar.MONTH,10);

      //the new da2 variable will hold the incremented date value.
      Date da2 = new Date(cal.getTimeInMillis());
      String monthname2 = new SimpleDateFormat("MMMM").format(da2);

      Hope this answers your question.

      Delete
    4. Thank You very much! (^///^)

      Delete
    5. can i identify the day based on the date? if can, how to?

      Delete
    6. Is there anyway that can write and read the Month and Year in different column into access database? If can please teach me, Urgent! Thank You.

      Delete
    7. Sorry Zack I cannot find answer for that.

      Delete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Hello bro, My name is chandran and i am currently working on my java assignment. i hav this problem where i cant insert the date frm jdatechooser to my Ms access 2007 database..

    My Code is like this :

    String Location = (String)cmbLocation.getSelectedItem(); String Type = (String)cmbTicketType.getSelectedItem(); Calendar cal = jDateChooser2.getCalendar();

    int datevar = cal.get(Calendar.DATE);
    int monthvar = cal.get(Calendar.MONTH);
    int yearvar = cal.get(Calendar.YEAR);
    String dateNow =datevar+"/"+monthvar+"/"+yearvar;

    try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:odbc:Database143"); stat = connection.createStatement(); String sql= ("INSERT into Purchase(Location,TicketType,Date) values('"+Location+"','"+Type+"','"+monthvar+"')");
    stat.execute(sql);

    JOptionPane.showMessageDialog(null, "Information recorded Succesfull.");
    dispose();
    new Payment().setVisible(true);

    }catch (ClassNotFoundException | SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, e); } }

    My error is : Syntax Error in INSERT INTO Statement.


    please help bro..

    ReplyDelete
    Replies
    1. by the way the sql statement i have changed t statement frm

      ("INSERT into Purchase(Location,TicketType,Date) values('"+Location+"','"+Type+"','"+monthvar+"')");

      to

      ("INSERT into Purchase(Location,TicketType,Date) values('"+Location+"','"+Type+"','"+dateNow+"')");

      Still not working

      Delete
    2. Hi Chandran. Try this statement.

      INSERT into Purchase(Location,TicketType,Date) values('Location','Type','dateNow');

      Delete
    3. or this statement

      INSERT into Purchase(Location,TicketType,Date) values('Location','Type','monthvar');

      Delete
    4. tried these code, same error pop out.

      Delete
    5. when i try to just insert location and tickettype into database, it do save the record successfully. the problem arise wen i include date.

      Delete
    6. How about this one?

      String sql= ("INSERT into Purchase(Location,TicketType,Date) values(Location,Type,monthvar)");

      Delete
    7. did not work out..same error appear. :'(

      Delete
    8. Sorry dude, I guess its probably due to type mismatch between monthvar variable and the corresponding column type in the access table.

      Delete
    9. hi there,I followed the your suggested method for jdatechooser which went smooth except for a line where it gives an error at line " Calendar cal = jDateChooser1.getCalendar();" the error i get on this line is "cannot find symbol method getCalendar()". My code given below:
      Class.forName("smallsql.database.SSDriver");
      connection = DriverManager.getConnection("jdbc:smallsql:C:\\TESTdb");
      statement = connection.createStatement();
      JOptionPane.showMessageDialog(null, "TESTING 1");
      Calendar cal = jDateChooser1.getCalendar();
      int datevar = cal.get(Calendar.DATE);

      int monthvar = cal.get(Calendar.MONTH);
      int yearvar = cal.get(Calendar.YEAR);
      jLabel2.setText("Date is " + datevar + ", Month is " + monthvar + " and Year is "+ yearvar + ".");

      I have already defined " jDateChooser1 = new com.toedter.calendar.JDateChooser();"

      Why do i get this error ,plz reply asap
      Thank u

      Delete
    10. why does "Calendar cal = jDateChooser1.getCalendar();"
      give error that it cannot find symbol getCalendar method, followed entire process correctly,please help asap

      Delete
  7. hi,
    i am developing swing app with jdatecjooser bt keyevent is not working for datechooser, is there any extra procedure for adding keypress event, I write code as
    dat1 = new com.toedter.calendar.JDateChooser();

    dat1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(java.awt.event.KeyEvent evt) {
    dat1KeyPressed(evt);
    }
    });


    private void dat1KeyPressed(java.awt.event.KeyEvent evt) {
    if (evt.getKeyCode() == KeyEvent.VK_ENTER||evt.getKeyCode() == KeyEvent.VK_RIGHT) {
    }
    if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {

    }
    }

    ReplyDelete
  8. very well explained

    ReplyDelete
  9. how to add jdate chooser date
    in database through netbeans in java

    ReplyDelete
  10. Thank you! I was surprised to see that Swing doesn't have its own date chooser and this really helped :)

    ReplyDelete
  11. Hi! Anyone knows how to resize the window of calendar? Its too big in my project;;; thanks

    ReplyDelete
  12. hi .my name bala i want you help i used jcalanderchooser
    i want output 01/02/2013 ,but is came in 1/1(means feb)/2013
    pls help any idea

    ReplyDelete
  13. hi, i would like to know how to make a cell editable in a JCalendar. for e.g i want to make a calendar planner,

    thx
    ra'essah

    ReplyDelete
  14. Tnx a lot for this, you have saved me a lot of time!

    ReplyDelete
  15. Ecorptrainings.com provides JAVA SWING in hyderabad with best faculties on real time projects. We give the best online trainingamong the JAVA SWING in Hyderabad. Classroom Training in Hyderabad India

    ReplyDelete
  16. i need to choose only month and year is jcalender support that?
    reply

    ReplyDelete
  17. thanks for this good tutorial!

    ReplyDelete
  18. I just got done following your tutorial, when I create the actionperformed for the button it gives me an error on this line:

    Calendar cal = mydatechooser.getCalendar();

    Saying that it cannot find the "mydatechooser" class.
    I am using Netbeans 7.2.1 and setup the class just as instructed. Any ideas?

    Thank You

    ReplyDelete
  19. hi all!
    i have a problem with jdatechooser, when i add date with format (yyyy-mm-dd, it same date format int mysql), but i havae a error:
    com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: 'Tue Jan 01 00:01:00 ICT 2013' for column 'day' at row 1
    how to fix it please help me...thank you.

    ReplyDelete
  20. hii,
    I want to know how to get the selected date from JCalendar and stored in the MySQL database.
    plzz help.......

    ReplyDelete

Post a Comment

Popular posts from this blog

Configuring Google Cardboard to work with Ant VR Headset for Lenovo Vibe K4 Note

Let me make it short. Open the Google Cardboard app from your Lenovo Vibe K4 Note. Go to Switch Viewer option and scan the following QR code. This makes Google Cardboard app to work perfectly with Ant VR Headset. Thanks to this Quora thread . Note : Dont use the inbuilt VR mode and Google Cardboard together. VR mode tries to make the whole android experience viewable through VR headset whereas Google Cardboard only produces VR experience for selective apps with Cardboard compatibility. So they dont work at the same time. Nothing goes wrong even if you activate them together, you only see VRception. Dont use default Ant VR app As mentioned in the Quora thread, dont use Ant VR app. It looks fishy and amateurish. May be its even a spying venture of PLA. who knows. Difference between 360 and 3D videos? If you open 360 videos from Google Cardboard you can watch selected 360 videos (like this one ), where you can rotate your head and look everywhere within t

Honda CB Twister India : A Quick Review

I came across a dozen reviews of Honda CB Twister on web and finally decided to buy it. I owned it on last March, 2012. It costed around ₹63,000 with disc brakes, alloy wheels, road tax and stuffs. The reason why I have included ‘India’ in title is because Twister is also available as Honda CB110 in other countries. Here is my short account on my experience with Twister. Mileage Mileage is a very essential part of my riding experience. I travel around 200 Kms every week, so fuel expenses shouldn't make me bankrupt. Twister’s 60 – 65 KmpL mileage is one of the factors that influenced my choice while buying. Anyway in advertisements its claimed to be 70KmpL.   Engine Nowadays its a increasing trend to see Indians going for high end bikes, but in my case I am good with medium performance engines. Twister’s 110CC engine makes riding smooth up to 55Kmph speed, beyond that Honda Twister turns in to a Honda Vibrator. Considering the fact that I’m not an adrenalized rider,