Friday 14 February 2014

Java: Display Calendar to pick a date using JXDatePicker


How do we display such a calendar in Java desktop based application?

The easiest way to do this is to use JXDatePicker. User can use JXDatePicker to select a date similar to a JComboBox. The selected date appears in a textbox as shown in the image above. 

NOTE: For using JXDatePicker download and use the SwingX jar in your project.
SwingX can be downloaded from this link

Add the jar that you downloaded from the above link to your project. Jar can be added following link -> this post

Here is a short program which demonstrates the usage of JXDatePicker

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

use picker.getDate() to get the user entered date.

2 comments:

  1. how can you stored date into database using above

    ReplyDelete
  2. how to store chosen date(using JXDatePicker) into database?

    ReplyDelete