Calendar in java swing

Calendar Implementation :Swing GUI Based java program

A calendar is a system of organizing days for social, religious, commercial, or administrative purposes. This is done by giving names to periods of time , typically days ,weeks,months and years . A date is the designation of a single, specific day within such a system. Periods in a calendar (such as years and months) are usually, though not necessarily, synchronized with the cycle of thee sun or the moon . Many civilizations and societies have devised a calendar, usually derived from other calendars on which they model their systems, suited to their particular needs.

A calendar is also a physical device (often paper). This is the most common usage of the word. Other similar types of calendars can include computerized systems, which can be set to remind the user of upcoming events and appointments.

The English word calendar is derived from the Latin word kalendae , which was the Latin name of the first day of every month.

There is a built in calendar class in java found in the java.util package , under the name calendar. A Calendar object can produce all the calendar field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). Calendar defines the range of values returned by certain calendar fields, as well as their meaning. For example, the first month of the calendar system has value MONTH == JANUARY for all calendars.

Читайте также:  Javascript rest api test

One thing to notice in the calendar class is the difference between roll() and add() .

Calendar.roll()
Changes a specific unit and leaves ‘larger’ (in terms of time-month is ‘larger’ than day) units unchanged. The API example is that given a date of August 31, 1999, rolling by (Calendar.MONTH, 8) yields April 30, 1999. That is, the DAY was changed to meet April’s maximum, but the ‘larger’ unit, YEAR, was unchanged.

Calendar.add()
Will cause the next ‘larger’ unit to change, if necessary. That is, given a date of August 31, 1999, add(Calendar.MONTH, 8) yields April 30, 2000. add() also forces a recalculation of milliseconds and all fields.

Calendar is a abstract class, and you cannot use the constructor to create an instance. Instead, you use the static method Calendar.getInstance() to instantiate an implementation sub-class.

* Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with

Looking into the source code reveals that: getInstance() returns a GregorianCalendar instance for all locales, (except BuddhistCalendar for Thai («th_TH») and JapaneseImperialCalendar for Japanese («ja_JP»)).

The most important method in Calendar is get ( int calendarField ), which produces an int . The calendarField are defined as static constant .

calendar java based program

import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class CalendarProgram static JLabel lblMonth, lblYear; static JButton btnPrev, btnNext; static JTable tblCalendar; static JComboBox cmbYear; static JFrame frmMain; static Container pane; static DefaultTableModel mtblCalendar; //Table model static JScrollPane stblCalendar; //The scrollpane static JPanel pnlCalendar; static int realYear, realMonth, realDay, currentYear, currentMonth; public static void main (String args[]) //Look and feel try UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());> catch (ClassNotFoundException e) <> catch (InstantiationException e) <> catch (IllegalAccessException e) <> catch (UnsupportedLookAndFeelException e) <> //Prepare frame frmMain = new JFrame ("Gestionnaire de clients"); //Create frame frmMain.setSize(330, 375); //Set size to 400x400 pixels pane = frmMain.getContentPane(); //Get content pane pane.setLayout(null); //Apply null layout frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close when X is clicked //Create controls lblMonth = new JLabel ("January"); lblYear = new JLabel ("Change year:"); cmbYear = new JComboBox(); btnPrev = new JButton ("<<"); btnNext = new JButton (">>"); mtblCalendar = new DefaultTableModel()public boolean isCellEditable(int rowIndex, int mColIndex)return false;>>; tblCalendar = new JTable(mtblCalendar); stblCalendar = new JScrollPane(tblCalendar); pnlCalendar = new JPanel(null); //Set border pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar")); //Register action listeners btnPrev.addActionListener(new btnPrev_Action()); btnNext.addActionListener(new btnNext_Action()); cmbYear.addActionListener(new cmbYear_Action()); //Add controls to pane pane.add(pnlCalendar); pnlCalendar.add(lblMonth); pnlCalendar.add(lblYear); pnlCalendar.add(cmbYear); pnlCalendar.add(btnPrev); pnlCalendar.add(btnNext); pnlCalendar.add(stblCalendar); //Set bounds pnlCalendar.setBounds(0, 0, 320, 335); lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 100, 25); lblYear.setBounds(10, 305, 80, 20); cmbYear.setBounds(230, 305, 80, 20); btnPrev.setBounds(10, 25, 50, 25); btnNext.setBounds(260, 25, 50, 25); stblCalendar.setBounds(10, 50, 300, 250); //Make frame visible frmMain.setResizable(false); frmMain.setVisible(true); //Get real month/year GregorianCalendar cal = new GregorianCalendar(); //Create calendar realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day realMonth = cal.get(GregorianCalendar.MONTH); //Get month realYear = cal.get(GregorianCalendar.YEAR); //Get year currentMonth = realMonth; //Match month and year currentYear = realYear; //Add headers String[] headers = "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat">; //All headers for (int i=0; i7; i++) mtblCalendar.addColumn(headers[i]); > tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background //No resize/reorder tblCalendar.getTableHeader().setResizingAllowed(false); tblCalendar.getTableHeader().setReorderingAllowed(false); //Single cell selection tblCalendar.setColumnSelectionAllowed(true); tblCalendar.setRowSelectionAllowed(true); tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Set row/column count tblCalendar.setRowHeight(38); mtblCalendar.setColumnCount(7); mtblCalendar.setRowCount(6); //Populate table for (int i=realYear-100; irealYear+100; i++) cmbYear.addItem(String.valueOf(i)); > //Refresh calendar refreshCalendar (realMonth, realYear); //Refresh calendar > public static void refreshCalendar(int month, int year) //Variables String[] months = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December">; int nod, som; //Number Of Days, Start Of Month //Allow/disallow buttons btnPrev.setEnabled(true); btnNext.setEnabled(true); if (month == 0 && year  realYear-10)btnPrev.setEnabled(false);> //Too early if (month == 11 && year >= realYear+100)btnNext.setEnabled(false);> //Too late lblMonth.setText(months[month]); //Refresh the month label (at the top) lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 180, 25); //Re-align label with calendar cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box //Clear table for (int i=0; i6; i++) for (int j=0; j7; j++) mtblCalendar.setValueAt(null, i, j); > > //Get first day of month and number of days GregorianCalendar cal = new GregorianCalendar(year, month, 1); nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH); som = cal.get(GregorianCalendar.DAY_OF_WEEK); //Draw calendar for (int i=1; inod; i++) int row = new Integer((i+som-2)/7); int column = (i+som-2)%7; mtblCalendar.setValueAt(i, row, column); > //Apply renderers tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer()); > static class tblCalendarRenderer extends DefaultTableCellRenderer public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column) super.getTableCellRendererComponent(table, value, selected, focused, row, column); if (column == 0 || column == 6) //Week-end setBackground(new Color(255, 220, 220)); > else //Week setBackground(new Color(255, 255, 255)); > if (value != null) if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear) //Today setBackground(new Color(220, 220, 255)); > > setBorder(null); setForeground(Color.black); return this; > > static class btnPrev_Action implements ActionListener public void actionPerformed (ActionEvent e) if (currentMonth == 0) //Back one year currentMonth = 11; currentYear -= 1; > else //Back one month currentMonth -= 1; > refreshCalendar(currentMonth, currentYear); > > static class btnNext_Action implements ActionListener public void actionPerformed (ActionEvent e) if (currentMonth == 11) //Foward one year currentMonth = 0; currentYear += 1; > else //Foward one month currentMonth += 1; > refreshCalendar(currentMonth, currentYear); > > static class cmbYear_Action implements ActionListener public void actionPerformed (ActionEvent e) if (cmbYear.getSelectedItem() != null) String b = cmbYear.getSelectedItem().toString(); currentYear = Integer.parseInt(b); refreshCalendar(currentMonth, currentYear); > > > > 

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

How to use JDatePicker to display calendar component

This tutorial shows you how to use the JDatePicker open-source library in order to display a calendar component in Java Swing programs with some necessary customizations. You will end up creating the following program:

calendar component demo

1. Quick start with JDatePicker

Click here to download the JDatePicker library from SourceForge. The latest version as of now is 1.3.2. Extract the downloaded archive JDatePicker-1.3.2-dist.zip , and then find and add the jdatepicker-1.3.2.jar file to your project’s classpath.

It’s pretty simple to create and add a date picker component to a container, i.e. a JFrame. It involves in choosing an appropriate DateModel which is required by a JDatePanelImpl which is required by a JDatePickerImpl — which is then added to the container. For example, the following code snippet creates a date picker component using the UtilDateModel , and then adds it to the frame:

UtilDateModel model = new UtilDateModel(); JDatePanelImpl datePanel = new JDatePanelImpl(model); JDatePickerImpl datePicker = new JDatePickerImpl(datePanel); frame.add(datePicker);

date picker component

It contains a disabled, read-only text field on the left, and an ellipsis button that will pop up a calendar when clicked:

Calendar

date selected

2. Dealing with Date Models

The JDatePicker library provides three date models which correspond to three date time types in Java:

  • UtilDateModel : the date picker will return the selected date as an object of type java.util.Date .
  • CalendarDateModel : the date picker will return the selected date as an object of type java.util.Calendar .
  • SqlDateModel : the date picker will return the selected date as an object of type java.sql.Date .

the JDatePickerImpl returns the selected date object of appropriate type. For example, the following statement gets the selected date in case the model is UtilDateModel :

Date selectedDate = (Date) datePicker.getModel().getValue();
Calendar selectedValue = (Calendar) datePicker.getModel().getValue(); Date selectedDate = selectedValue.getTime();
java.sql.Date selectedDate = (java.sql.Date) datePicker.getModel().getValue();

3. Setting initial date

UtilDateModel model = new UtilDateModel(); model.setDate(1990, 8, 24);

That sets the initial date to September 24, 1990 (because in Java, the month number is zero-based). Result:

Setting initial date on the calendar

If you want to set initial date for the text field, use the following statement:

setting initial date on the text field

4. Customizing the date format

The default format of the date shown in the text field may not suite your need. In such case, you can create your own class that extends the javax.swing.JFormattedTextField.AbstractFormatter class. For example:

package net.codejava.swing; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JFormattedTextField.AbstractFormatter; public class DateLabelFormatter extends AbstractFormatter < private String datePattern = "yyyy-MM-dd"; private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern); @Override public Object stringToValue(String text) throws ParseException < return dateFormatter.parseObject(text); >@Override public String valueToString(Object value) throws ParseException < if (value != null) < Calendar cal = (Calendar) value; return dateFormatter.format(cal.getTime()); >return ""; > >

As you can see, this class overrides the stringToValue() method to parse a String to a Date object; and overrides the valueToString() method to format the Calendar object to a String . The date pattern to use is yyy-MM-dd.

And pass an instance of this custom class when constructing the date picker component as follows:

JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());

customized date format

You can download the Java source files under the attachment section.

References:

Other Java Swing Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Оцените статью