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.
- 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.
- 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.
- 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.
- 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’.
- 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.
- 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.
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.
- 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’.
- Now click on Add from Library… button to select the Jcalendar library that we created already.
- 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.
- 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.
.
- 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.
- 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.
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
could u please tell me how to add JCalendar in gwt applications using eclipse...please give me reply soon its urgent in my application .
ReplyDeleteSorry I dont know the answer yet for your query as I'm not familiar with GWT.
Deletehi all,
ReplyDeletei 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...???
Hi Karan, I have included the source code for that. Anyway here is the snippet for your reference.
Deleteprivate 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
}
I have a problem, if I want to make a new CellEditor for the JTable, I write:
ReplyDeleteTableCellEditor 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?
ok I solved the problem:
Deleteprivate com.toedter.calendar.JDateChooserCellEditor jDateEditor = new com.toedter.calendar.JDateChooserCellEditor();
jTable.getColumn("Date").setCellRenderer(DateRenderer);
ok Sam. Anyway you can use a import statement at the beginning of the Class like this.
Deleteimport com.toedter.calendar.JDateChooserCellEditor;
Is there anyway to display the month in word, like month = january.
ReplyDeleteYes Zack it possible
DeleteCalendar 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;
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?
DeleteJust simple arithmetics.
DeleteCalendar 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.
Thank You very much! (^///^)
Deletecan i identify the day based on the date? if can, how to?
DeleteIs 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.
DeleteSorry Zack I cannot find answer for that.
DeleteThis comment has been removed by the author.
ReplyDeleteHello 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..
ReplyDeleteMy 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..
by the way the sql statement i have changed t statement frm
Delete("INSERT into Purchase(Location,TicketType,Date) values('"+Location+"','"+Type+"','"+monthvar+"')");
to
("INSERT into Purchase(Location,TicketType,Date) values('"+Location+"','"+Type+"','"+dateNow+"')");
Still not working
Hi Chandran. Try this statement.
DeleteINSERT into Purchase(Location,TicketType,Date) values('Location','Type','dateNow');
or this statement
DeleteINSERT into Purchase(Location,TicketType,Date) values('Location','Type','monthvar');
tried these code, same error pop out.
Deletewhen i try to just insert location and tickettype into database, it do save the record successfully. the problem arise wen i include date.
DeleteHow about this one?
DeleteString sql= ("INSERT into Purchase(Location,TicketType,Date) values(Location,Type,monthvar)");
did not work out..same error appear. :'(
DeleteSorry dude, I guess its probably due to type mismatch between monthvar variable and the corresponding column type in the access table.
Deletehi 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:
DeleteClass.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
why does "Calendar cal = jDateChooser1.getCalendar();"
Deletegive error that it cannot find symbol getCalendar method, followed entire process correctly,please help asap
hi,
ReplyDeletei 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) {
}
}
its urgent please..
Deletevery well explained
ReplyDeletehow to add jdate chooser date
ReplyDeletein database through netbeans in java
Thank you! I was surprised to see that Swing doesn't have its own date chooser and this really helped :)
ReplyDeleteHi! Anyone knows how to resize the window of calendar? Its too big in my project;;; thanks
ReplyDeletehi .my name bala i want you help i used jcalanderchooser
ReplyDeletei want output 01/02/2013 ,but is came in 1/1(means feb)/2013
pls help any idea
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,
ReplyDeletethx
ra'essah
Tnx a lot for this, you have saved me a lot of time!
ReplyDeleteEcorptrainings.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
ReplyDeletei need to choose only month and year is jcalender support that?
ReplyDeletereply
thanks for this good tutorial!
ReplyDeleteI just got done following your tutorial, when I create the actionperformed for the button it gives me an error on this line:
ReplyDeleteCalendar 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
hi all!
ReplyDeletei 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.
hii,
ReplyDeleteI want to know how to get the selected date from JCalendar and stored in the MySQL database.
plzz help.......