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.
/******************************************************************************
public class Calendar {
public static int day(int month, int day, int year) {
int y = year - (14 - month) / 12;
int x = y + y/4 - y/100 + y/400;
int m = month + 12 * ((14 - month) / 12) - 2;
int d = (day + x + (31*m)/12) % 7;
return d;
}
public static boolean isLeapYear(int year) {
if ((year % 4 == 0) && (year % 100 != 0)) return true;
if (year % 400 == 0) return true;
return false;
}
public static void main(String[] args) {
int month = Integer.parseInt(args[0]);
int year = Integer.parseInt(args[1]);
String[] months = {
"",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
int[] days = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
if (month == 2 && isLeapYear(year)) days[month] = 29;
StdOut.println(" " + months[month] + " " + year);
StdOut.println(" S M Tu W Th F S");
int d = day(month, 1, year);
for (int i = 0; i < d; i++)
StdOut.print(" ");
for (int i = 1; i <= days[month]; i++) {
StdOut.printf("%2d ", i);
if (((i + d) % 7 == 0) || (i == days[month])) StdOut.println();
}
}
}
ANOTHER CODE FOR CALENDAR
// Demonstrate Calendar
import java.util.Calendar;
class CalendarDemo {
public static void main(String args[]) {
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
// Create a calendar initialized with the
// current date and time in the default
// locale and timezone.
Calendar calendar = Calendar.getInstance();
// Display current time and date information.
System.out.print("Date: ");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
// Set the time and date information and display it.
calendar.set(Calendar.HOUR, 10);
calendar.set(Calendar.MINUTE, 29);
calendar.set(Calendar.SECOND, 22);
System.out.print("Updated time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
}
}
Sample output is shown here:
Date: Jan 25 1999
Time: 11:24:25
Updated time: 10:29:22
ANOTHER CODE FOR CALENDAR
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; i<7; 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; i<=realYear+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; i<6; i++){
for (int j=0; j<7; 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; i<=nod; 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);
}
}
}
}
ANOTHER CODE FOR CALENDAR
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class SwingCalendar extends JFrame {
DefaultTableModel model;
Calendar cal = new GregorianCalendar();
JLabel label;
SwingCalendar() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Swing Calandar");
this.setSize(300,200);
this.setLayout(new BorderLayout());
this.setVisible(true);
label = new JLabel();
label.setHorizontalAlignment(SwingConstants.CENTER);
JButton b1 = new JButton("<-");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cal.add(Calendar.MONTH, -1);
updateMonth();
}
});
JButton b2 = new JButton("->");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cal.add(Calendar.MONTH, +1);
updateMonth();
}
});
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(b1,BorderLayout.WEST);
panel.add(label,BorderLayout.CENTER);
panel.add(b2,BorderLayout.EAST);
String [] columns = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
model = new DefaultTableModel(null,columns);
JTable table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
this.add(panel,BorderLayout.NORTH);
this.add(pane,BorderLayout.CENTER);
this.updateMonth();
}
void updateMonth() {
cal.set(Calendar.DAY_OF_MONTH, 1);
String month = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int year = cal.get(Calendar.YEAR);
label.setText(month + " " + year);
int startDay = cal.get(Calendar.DAY_OF_WEEK);
int numberOfDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int weeks = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
model.setRowCount(0);
model.setRowCount(weeks);
int i = startDay-1;
for(int day=1;day<=numberOfDays;day++){
model.setValueAt(day, i/7 , i%7 );
i = i + 1;
}
}
public static void main(String[] arguments) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingCalendar sc = new SwingCalendar();
}
}
ANOTHER CALENDAR CODE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
/**
* This class represents the graphical user interface (GUI) for the scheduling
* program, allowing the user to view, add, and remove courses from a schedule.
*
* @author Marty Stepp
* @version Spring 2011 v1.0
*/
public class SchedulerGui {
// the file name from which to read the student's courses
private static final String COURSES_FILE_NAME = "courses.txt";
// if true, grays out Drop button unless a course is selected in the table;
// disabling by default because it relies on lots of student's code working
private static final boolean SELECTION_ENABLING = false;
private JFrame frame;
private JTable scheduleTable;
private JButton add;
private JButton drop;
private JButton save;
private JLabel credits;
private Schedule schedule;
private ScheduleTableModel model;
/**
* Constructs a new GUI to display items from the given catalog.
* @param catalog The store catalog to use
* @pre catalog != null
*/
public SchedulerGui() {
load();
createComponents();
setupEvents();
performLayout();
frame.setVisible(true);
}
// Constructs all of the graphical components to reside in the window frame
private void createComponents() {
model = new ScheduleTableModel(schedule);
scheduleTable = new JTable(model);
// set up the table column headings
JTableHeader header = scheduleTable.getTableHeader();
header.setBackground(Color.YELLOW.brighter());
header.setReorderingAllowed(false);
TableColumnModel columnModel = scheduleTable.getColumnModel();
for (int c = 0; c < model.getColumnCount(); c++) {
TableColumn column = columnModel.getColumn(c);
Weekday day = ScheduleTableModel.toDay(c);
column.setHeaderValue(day == null ? "" : String.valueOf(day));
}
ListSelectionModel selectionModel = scheduleTable.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// set up the various buttons
add = new JButton("Add");
add.setMnemonic('A');
drop = new JButton("Drop");
drop.setMnemonic('D');
save = new JButton("Save");
save.setMnemonic('S');
if (SELECTION_ENABLING) {
drop.setEnabled(false);
}
credits = new JLabel("");
credits.setHorizontalAlignment(SwingConstants.CENTER);
updateCredits();
// window frame for the overall display
frame = new JFrame("CSE 331 Course Scheduler");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Sets up event handlers on all relevant components in the window.
private void setupEvents() {
// when the user checks/unchecks the Discount box, inform the shopping cart
ActionListener listener = new ScheduleButtonListener();
add.addActionListener(listener);
drop.addActionListener(listener);
save.addActionListener(listener);
ListSelectionListener selection = new ScheduleSelectionListener();
if (SELECTION_ENABLING) {
scheduleTable.getSelectionModel().addListSelectionListener(selection);
}
}
private class ScheduleSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent event) {
int row = scheduleTable.getSelectedRow();
int column = scheduleTable.getSelectedColumn();
if (row < 0 || column < 0) {
return;
}
boolean hasCourse = model.getValueAt(row, column) != null;
drop.setEnabled(hasCourse);
}
}
// Constructs containers to do the layout and positioning of the components
// in the window. Also creates the display components for the catalog items.
private void performLayout() {
// south panel stores the ORDER TOTAL label and discount checkbox
JPanel south = new JPanel(new GridLayout(0, 1));
south.add(credits);
JPanel southBottom = new JPanel(new FlowLayout());
southBottom.add(add);
southBottom.add(drop);
southBottom.add(save);
south.add(southBottom);
// frame's content pane stores overall layout for the window
Container contentPane = frame.getContentPane();
contentPane.add(scheduleTable.getTableHeader(), BorderLayout.NORTH);
contentPane.add(scheduleTable, BorderLayout.CENTER);
contentPane.add(south, BorderLayout.SOUTH);
frame.pack();
SchedulerInputPane.center(frame);
}
// Handles the adding of a course to the schedule.
private void add() {
// pop up an input dialog box to read the course info
String[] inputNames = {"name", "credits", "days (e.g. MWF)", "start time (e.g. 12:30 PM)", "duration (min)"};
Class<?>[] inputTypes = {String.class, Integer.TYPE, String.class, String.class, Integer.TYPE};
SchedulerInputPane pane = new SchedulerInputPane();
boolean ok = pane.showInputDialog(frame, "Add a course",
"Tell us more about the course you want to add:",
inputNames, inputTypes);
if (!ok) {
return;
}
// use the course info from the dialog box to create the course
try {
// read info from dialog
String name = pane.getString("name");
int credits = pane.getInt("credits");
String daysStr = pane.getString("days (e.g. MWF)");
Set<Weekday> days = ScheduleIO.weekdaysFromShortNames(daysStr);
String startTimeStr = pane.getString("start time (e.g. 12:30 PM)");
Time startTime = Time.fromString(startTimeStr);
int duration = pane.getInt("duration (min)");
// create course and add to schedule
Course course = new Course(name, credits, days, startTime, duration);
model.addCourse(course);
updateCredits();
} catch (ScheduleConflictException e) {
error(e, "Schedule conflict while trying to add your course.");
} catch (IllegalArgumentException e) {
error(e, "Illegal argument in new course information.\n"
+ "Perhaps you left a field blank or typed an improper value.\n\n"
+ "(see the console for more details about this error.)");
} catch (Exception e) {
error(e, "Error while reading new course information.\n"
+ "Perhaps you left a field blank or typed an improper value.\n\n"
+ "(see the console for more details about this error.)");
}
}
// Handles the removal of a course from the schedule.
private void drop() {
int row = scheduleTable.getSelectedRow();
int column = scheduleTable.getSelectedColumn();
if (row < 0 || column < 0) {
return;
}
model.removeCourse(row, column);
updateCredits();
}
// A helper to pop up an error message box when the given exception is thrown.
// The given error message is displayed to the user along with the exception.
// The exception's stack trace is also printed to stderr.
private void error(Exception exception, String message) {
JOptionPane.showMessageDialog(frame, message + "\n\n" + exception.toString(),
"Error", JOptionPane.ERROR_MESSAGE);
exception.printStackTrace();
}
// A helper to pop up an error message box to show the given error message.
private void error(String message) {
JOptionPane.showMessageDialog(frame, message,
"Error", JOptionPane.ERROR_MESSAGE);
}
// Loads the user's courses from COURSES_FILE_NAME and puts the
// results into the user's current schedule.
private void load() {
try {
schedule = ScheduleIO.load(new FileInputStream(COURSES_FILE_NAME));
updateCredits();
} catch (Exception e) {
// also try loading from within a JAR
InputStream stream = SchedulerGui.class.getResourceAsStream("/" + COURSES_FILE_NAME);
if (stream != null) {
try {
schedule = ScheduleIO.load(stream);
} catch (Exception e2) {
System.err.println(e2);
}
}
if (schedule == null) {
error("An error occurred while loading your course schedule: \n" + e
+ "\n\n(NOTE: Place any input .txt files in the following directory:)\n" + System.getProperty("user.dir"));
schedule = new Schedule();
}
}
}
// Saves the user's current course schedule into COURSES_FILE_NAME.
private void save() {
String[] orders = {"By name", "By credits", "By day/time"};
int result = JOptionPane.showOptionDialog(frame,
"In what order should the courses be stored?",
"Save order?",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
orders,
"By name");
if (result < 0) {
return;
}
// use the button clicked to decide which Comparator to create/use
Comparator<Course> compare;
if (result == 0) {
compare = new CourseNameComparator();
} else if (result == 1) {
compare = new CourseCreditComparator();
} else {
compare = new CourseTimeComparator();
}
// actually save it now!
try {
schedule.save(new PrintStream(new File(COURSES_FILE_NAME)), compare);
JOptionPane.showMessageDialog(frame, "Your course schedule was saved "
+ "successfully to " + COURSES_FILE_NAME + ".");
} catch (Exception ioe) {
JOptionPane.showMessageDialog(frame,
"An error occurred while saving your course schedule: \n" + ioe,
"Input/output error", JOptionPane.ERROR_MESSAGE);
}
}
// Updates the label displaying the student's current total credits.
private void updateCredits() {
credits.setText("Total credits: " + schedule.totalCredits());
}
// An action listener to respond to clicks on the buttons in the window.
private class ScheduleButtonListener implements ActionListener {
/**
* Called when a button is clicked in the window.
* Delegates to methods of the SchedulerGui for saving, adding, etc.
* @event details about which button was clicked
*/
public void actionPerformed(ActionEvent event) {
Object src = event.getSource();
if (src == drop) {
drop();
} else if (src == add) {
add();
} else if (src == save) {
save();
}
}
}
}
No comments:
Post a Comment