1+ import java .util .*;
2+ import java .awt .*;
3+ import java .awt .event .*;
4+ import javax .swing .*;
5+ import javax .swing .table .*;
6+
7+ public class SwingCalendar extends JFrame {
8+
9+ DefaultTableModel model ;
10+ Calendar cal = new GregorianCalendar ();
11+ JLabel label ;
12+
13+ SwingCalendar () {
14+
15+ this .setDefaultCloseOperation (JFrame .EXIT_ON_CLOSE );
16+ this .setTitle ("Swing Calandar" );
17+ this .setSize (300 ,200 );
18+ this .setLayout (new BorderLayout ());
19+ this .setVisible (true );
20+
21+
22+ label = new JLabel ();
23+ label .setHorizontalAlignment (SwingConstants .CENTER );
24+
25+ JButton b1 = new JButton ("<-" );
26+ b1 .addActionListener (new ActionListener () {
27+ public void actionPerformed (ActionEvent ae ) {
28+ cal .add (Calendar .MONTH , -1 );
29+ updateMonth ();
30+ }
31+ });
32+
33+ JButton b2 = new JButton ("->" );
34+ b2 .addActionListener (new ActionListener () {
35+ public void actionPerformed (ActionEvent ae ) {
36+ cal .add (Calendar .MONTH , +1 );
37+ updateMonth ();
38+ }
39+ });
40+
41+ JPanel panel = new JPanel ();
42+ panel .setLayout (new BorderLayout ());
43+ panel .add (b1 ,BorderLayout .WEST );
44+ panel .add (label ,BorderLayout .CENTER );
45+ panel .add (b2 ,BorderLayout .EAST );
46+
47+
48+ String [] columns = {"Sun" ,"Mon" ,"Tue" ,"Wed" ,"Thu" ,"Fri" ,"Sat" };
49+ model = new DefaultTableModel (null ,columns );
50+ JTable table = new JTable (model );
51+ JScrollPane pane = new JScrollPane (table );
52+
53+ this .add (panel ,BorderLayout .NORTH );
54+ this .add (pane ,BorderLayout .CENTER );
55+
56+ this .updateMonth ();
57+
58+ }
59+
60+ void updateMonth () {
61+ cal .set (Calendar .DAY_OF_MONTH , 1 );
62+
63+ String month = cal .getDisplayName (Calendar .MONTH , Calendar .LONG , Locale .US );
64+ int year = cal .get (Calendar .YEAR );
65+ label .setText (month + " " + year );
66+
67+ int startDay = cal .get (Calendar .DAY_OF_WEEK );
68+ int numberOfDays = cal .getActualMaximum (Calendar .DAY_OF_MONTH );
69+ int weeks = cal .getActualMaximum (Calendar .WEEK_OF_MONTH );
70+
71+ model .setRowCount (0 );
72+ model .setRowCount (weeks );
73+
74+ int i = startDay -1 ;
75+ for (int day =1 ;day <=numberOfDays ;day ++){
76+ model .setValueAt (day , i /7 , i %7 );
77+ i = i + 1 ;
78+ }
79+
80+ }
81+
82+ public static void main (String [] arguments ) {
83+ JFrame .setDefaultLookAndFeelDecorated (true );
84+ SwingCalendar sc = new SwingCalendar ();
85+ }
86+
87+ }
88+
0 commit comments