Java how to use jdatepicker to display calendar component
In Java Swing, you can use the JDatePicker component to display a calendar for date selection. Here's an example of how to use it:
First, you need to add the JDatePicker library to your project. You can download it from here: https://github.com/JDatePicker/JDatePicker
Once you have the library, you can create a JDatePicker component and add it to your UI. Here's an example:
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jdatepicker.JDatePicker;
import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilCalendarModel;
public class DatePickerExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// Create a panel with a flow layout
JPanel panel = new JPanel(new FlowLayout());
// Create a UtilCalendarModel with the current date
UtilCalendarModel model = new UtilCalendarModel();
model.setDate(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
// Create a JDatePanel with the UtilCalendarModel
JDatePanelImpl datePanel = new JDatePanelImpl(model);
// Create a JDatePicker with the JDatePanel
JDatePicker datePicker = new JDatePickerImpl(datePanel);
// Add the JDatePicker to the panel
panel.add(datePicker);
// Create a frame and add the panel to it
JFrame frame = new JFrame("Date Picker Example");
frame.add(panel);
frame.pack();
frame.setVisible(true);
});
}
}
In this example, we create a JPanel with a FlowLayout, which will contain the JDatePicker component. We then create a UtilCalendarModel with the current date, and a JDatePanelImpl with the UtilCalendarModel. Finally, we create a JDatePickerImpl with the JDatePanelImpl, and add it to the panel.
When you run this example, you will see a window with a JDatePicker component showing the current date. You can click on the calendar icon to display the calendar and select a different date. The selected date will be displayed in the JDatePicker component.
