public class CalendarIconExample extends JComponent { int SIZE = 60; Dimension dim = new Dimension(SIZE, SIZE); int nx, ny, width = 38, height = 38; Calendar cal; Font dateFont, dayFont, monthFont; FontMetrics date, day, month ; boolean showTime = true; String[] days ={"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"}; String[] months={"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", };
public CalendarIconExample(boolean show) { this(Calendar.getInstance(), show); } public CalendarIconExample(Calendar c, boolean show) { super(); cal = c; ny = 5; nx = 10; dateFont = new Font("Serif", Font.BOLD, 18); date = getFontMetrics(dateFont); dayFont = new Font("Book Antiqua", Font.BOLD, 10); day = getFontMetrics(dayFont); monthFont = new Font("Book Antiqua", Font.BOLD, 10); month = getFontMetrics(monthFont); } public void paint(Graphics graphics) { paintIcon(this, graphics, 0, 0); } public void paintIcon(Component component, Graphics g, int x, int y) { g.drawRect(x, y, dim.width - 2, dim.height - 2); g.setColor(Color.gray); g.fillRect(x + nx + 3, y + ny + 3, width, height); g.setColor(Color.white); g.fillRect(x + nx, y + ny, width, height); g.setColor(Color.black); if (showTime) super.paint(g);
String st = days[cal.get(Calendar.DAY_OF_WEEK) - 1]; g.setFont(dayFont); g.setColor(Color.red); int w = day.stringWidth(st); g.drawString(st, x + nx + ((width - w) / 2), y + ny + 10);
st = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)); g.setFont(dateFont); g.setColor(Color.black); w = date.stringWidth(st); g.drawString(st, x + nx + ((width - w) / 2), y + ny + 25);
st = months[cal.get(Calendar.MONTH)]; g.setFont(monthFont); g.setColor(Color.red); w = month.stringWidth(st); g.drawString(st, x + nx + ((width - w) / 2), y + ny + 35); } public static void main(String[] args) { JFrame frame = new JFrame("Calendar"); Container container= frame.getContentPane(); CalendarIconExample iconExample = new CalendarIconExample(true); container.add(iconExample); frame.setSize(100, 100); frame.show(); } }