
Display Dates in a Custom Calendar #4
Chapter 1, Basic JComponents
|
21
HACK
This loads the images in the constructor and sets up date formatters for the
month, year, and day. Override the
paintComponent( ) method to turn on
anti-aliasing, draw the background, and then draw the month and year for
the current date.
You’ll notice that there is a default date in case the devel-
oper doesn’t set one (always a good practice).
Draw the Days of the Month
The java.util.Calendar object handles all date calculations, so let’s start
there. You’ll need two calendars: one to represent the current date (
today)
and one that you update as you loop through the grid of dates (
cal). Here’s
what that looks like in code:
Calendar today = Calendar.getInstance( );
today.setTime(date);
Calendar cal = Calendar.getInstance( );
cal.setTime(date);
protected SimpleDateFormat year = new SimpleDateFormat("yyyy");
protected SimpleDateFormat day = new SimpleDateFormat("d");
protected Date date = new Date( );
public void setDate(Date date) {
this.date = date;
}
public CalendarHack( ) {
background = new ImageIcon("calendar.png").getImage( );
highlight = new ImageIcon("highlight.png").getImage( );
day_img = new ImageIcon("day.png").getImage( );
this.setPreferredSize(new Dimension(300,280));
}
public void paintComponent(Graphics g) {
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON); ...