This section illustrates you how to draw a calendar in SWT, showing current date.
SWT allows to create Calendar by using the java.util.Calendar class. The class CLabel draws the aligned text with different border styles. We are using this class to write the day and the days of week. The class GridLayout provides the configuration of GridData in the layout and the GridData sets the configuration fields.
For getting the number of days in the month, we have create a condition in the method getMonthDays(). If the month is 1, 3, 5, 7, 8, 10 or 12, it will return 31 days and if the month is 4, 6, 9 or 11, it will return 30 days. If the month is 2, then check if the month is leap, return 29 days otherwise return 28. To find whether the year is leap, we have create a method isLeap().
The gridLayout.numColumns specifies the number of columns in the layout. The method setLayoutData() sets the layout data. The gridData.horizontalSpan specifies the number of columns that the control will take up. The gridData.widthHint specifies the minimum width for the column and gridData.heightWidth specifies the minimum height for the row.
Following code displays the date format:
| SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss"); label.setText(dateFormat.format(new Date())); |
To display the current day, we have create a method setDisplayDay(). This method is called by the object of the class java.util.Calender. The method getInstance() gets the calendar with default time and locale.
Here is the code of CalendarExample.java
import java.text.*;
|
Output will be displayed as:

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Draw Calendar in SWT View All Comments
Post your Comment