大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
import java.util.Calendar;
创新互联建站长期为1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为茂南企业提供专业的成都网站建设、网站建设,茂南网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class CalendarPad extends JFrame implements MouseListener
{
int year,month,day;
Hashtable hashtable;
File file;
JTextField showDay[];
JLabel title[];
Calendar 日历;
int 星期几;
NotePad notepad=null;
Month 负责改变月;
Year 负责改变年;
String 星期[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
JPanel leftPanel,rightPanel;
public CalendarPad(int year,int month,int day)
{
leftPanel=new JPanel();
JPanel leftCenter=new JPanel();
JPanel leftNorth=new JPanel();
leftCenter.setLayout(new GridLayout(7,7));
rightPanel=new JPanel();
this.year=year;
this.month=month;
this.day=day;
负责改变年=new Year(this);
负责改变年.setYear(year);
负责改变月=new Month(this);
负责改变月.setMonth(month);
title=new JLabel[7];
showDay=new JTextField[42];
for(int j=0;j7;j++)
{
title[j]=new JLabel();
title[j].setText(星期[j]);
title[j].setBorder(BorderFactory.createRaisedBevelBorder());
leftCenter.add(title[j]);
}
title[0].setForeground(Color.red);
title[6].setForeground(Color.blue);
for(int i=0;i42;i++)
{
showDay[i]=new JTextField();
showDay[i].addMouseListener(this);
showDay[i].setEditable(false);
leftCenter.add(showDay[i]);
}
日历=Calendar.getInstance();
Box box=Box.createHorizontalBox();
box.add(负责改变年);
box.add(负责改变月);
leftNorth.add(box);
leftPanel.setLayout(new BorderLayout());
leftPanel.add(leftNorth,BorderLayout.NORTH);
leftPanel.add(leftCenter,BorderLayout.CENTER);
leftPanel.add(new Label("请在年份输入框输入所查年份(负数表示公元前),并回车确定"),
BorderLayout.SOUTH) ;
leftPanel.validate();
Container con=getContentPane();
JSplitPane split=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftPanel,rightPanel);
con.add(split,BorderLayout.CENTER);
con.validate();
hashtable=new Hashtable();
file=new File("日历记事本.txt");
if(!file.exists())
{
try{
FileOutputStream out=new FileOutputStream(file);
ObjectOutputStream objectOut=new ObjectOutputStream(out);
objectOut.writeObject(hashtable);
objectOut.close();
out.close();
}
catch(IOException e)
{
}
}
notepad=new NotePad(this);
rightPanel.add(notepad);
设置日历牌(year,month);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setVisible(true);
setBounds(100,50,524,285);
validate();
}
public void 设置日历牌(int year,int month)
{
日历.set(year,month-1,1);
星期几=日历.get(Calendar.DAY_OF_WEEK)-1;
if(month==1||month==2||month==3||month==5||month==7
||month==8||month==10||month==12)
{
排列号码(星期几,31);
}
else if(month==4||month==6||month==9||month==11)
{
排列号码(星期几,30);
}
else if(month==2)
{
if((year%4==0year%100!=0)||(year%400==0))
{
排列号码(星期几,29);
}
else
{
排列号码(星期几,28);
}
}
}
public void 排列号码(int 星期几,int 月天数)
{
for(int i=星期几,n=1;i星期几+月天数;i++)
{
showDay[i].setText(""+n);
if(n==day)
{
showDay[i].setForeground(Color.green);
showDay[i].setFont(new Font("TimesRoman",Font.BOLD,20));
}
else
{
showDay[i].setFont(new Font("TimesRoman",Font.BOLD,12));
showDay[i].setForeground(Color.black);
}
if(i%7==6)
{
showDay[i].setForeground(Color.blue);
}
if(i%7==0)
{
showDay[i].setForeground(Color.red);
}
n++;
}
for(int i=0;i星期几;i++)
{
showDay[i].setText("");
}
for(int i=星期几+月天数;i42;i++)
{
showDay[i].setText("");
}
}
public int getYear()
{
return year;
}
public void setYear(int y)
{
year=y;
notepad.setYear(year);
}
public int getMonth()
{
return month;
}
public void setMonth(int m)
{
month=m;
notepad.setMonth(month);
}
public int getDay()
{
return day;
}
public void setDay(int d)
{
day=d;
notepad.setDay(day);
}
public Hashtable getHashtable()
{
return hashtable;
}
public File getFile()
{
return file;
}
public void mousePressed(MouseEvent e)
{
JTextField source=(JTextField)e.getSource();
try{
day=Integer.parseInt(source.getText());
notepad.setDay(day);
notepad.设置信息条(year,month,day);
notepad.设置文本区(null);
notepad.获取日志内容(year,month,day);
}
catch(Exception ee)
{
}
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public static void main(String args[])
{
Calendar calendar=Calendar.getInstance();
int y=calendar.get(Calendar.YEAR);
int m=calendar.get(Calendar.MONTH)+1;
int d=calendar.get(Calendar.DAY_OF_MONTH);
new CalendarPad(y,m,d);
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Month extends Box implements ActionListener
{
int month;
JTextField showMonth=null;
JButton 下月,上月;
CalendarPad 日历;
public Month(CalendarPad 日历)
{
super(BoxLayout.X_AXIS);
this.日历=日历;
showMonth=new JTextField(2);
month=日历.getMonth();
showMonth.setEditable(false);
showMonth.setForeground(Color.blue);
showMonth.setFont(new Font("TimesRomn",Font.BOLD,16));
下月=new JButton("下月");
上月=new JButton("上月");
add(上月);
add(showMonth);
add(下月);
上月.addActionListener(this);
下月.addActionListener(this);
showMonth.setText(""+month);
}
public void setMonth(int month)
{
if(month=12month=1)
{
this.month=month;
}
else
{
this.month=1;
}
showMonth.setText(""+month);
}
public int getMonth()
{
return month;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==上月)
{
if(month=2)
{
month=month-1;
日历.setMonth(month);
日历.设置日历牌(日历.getYear(),month);
}
else if(month==1)
{
month=12;
日历.setMonth(month);
日历.设置日历牌(日历.getYear(),month);
}
showMonth.setText(""+month);
}
else if(e.getSource()==下月)
{
if(month12)
{
month=month+1;
日历.setMonth(month);
日历.设置日历牌(日历.getYear(),month);
}
else if(month==12)
{
month=1;
日历.setMonth(month);
日历.设置日历牌(日历.getYear(),month);
}
showMonth.setText(""+month);
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class NotePad extends JPanel implements ActionListener
{
JTextArea text;
JButton 保存日志,删除日志;
Hashtable table;
JLabel 信息条;
int year,month,day;
File file;
CalendarPad calendar;
public NotePad(CalendarPad calendar)
{
this.calendar=calendar;
year=calendar.getYear();
month=calendar.getMonth();
day=calendar.getDay();;
table=calendar.getHashtable();
file=calendar.getFile();
信息条=new JLabel(""+year+"年"+month+"月"+day+"日",JLabel.CENTER);
信息条.setFont(new Font("TimesRoman",Font.BOLD,16));
信息条.setForeground(Color.blue);
text=new JTextArea(10,10);
保存日志=new JButton("保存日志") ;
删除日志=new JButton("删除日志") ;
保存日志.addActionListener(this);
删除日志.addActionListener(this);
setLayout(new BorderLayout());
JPanel pSouth=new JPanel();
add(信息条,BorderLayout.NORTH);
pSouth.add(保存日志);
pSouth.add(删除日志);
add(pSouth,BorderLayout.SOUTH);
add(new JScrollPane(text),BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==保存日志)
{
保存日志(year,month,day);
}
else if(e.getSource()==删除日志)
{
删除日志(year,month,day);
}
}
public void setYear(int year)
{
this.year=year;
}
public int getYear()
{
return year;
}
public void setMonth(int month)
{
this.month=month;
}
public int getMonth()
{
return month;
}
public void setDay(int day)
{
this.day=day;
}
public int getDay()
{
return day;
}
public void 设置信息条(int year,int month,int day)
{
信息条.setText(""+year+"年"+month+"月"+day+"日");
}
public void 设置文本区(String s)
{
text.setText(s);
}
public void 获取日志内容(int year,int month,int day)
{
String key=""+year+""+month+""+day;
try
{
FileInputStream inOne=new FileInputStream(file);
ObjectInputStream inTwo=new ObjectInputStream(inOne);
table=(Hashtable)inTwo.readObject();
inOne.close();
inTwo.close();
}
catch(Exception ee)
{
}
if(table.containsKey(key))
{
String m=""+year+"年"+month+"月"+day+"这一天有日志记载,想看吗?";
int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(ok==JOptionPane.YES_OPTION)
{
text.setText((String)table.get(key));
}
else
{
text.setText("");
}
}
else
{
text.setText("无记录");
}
}
public void 保存日志(int year,int month,int day)
{
String 日志内容=text.getText();
String key=""+year+""+month+""+day;
String m=""+year+"年"+month+"月"+day+"保存日志吗?";
int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(ok==JOptionPane.YES_OPTION)
{
try
{
FileInputStream inOne=new FileInputStream(file);
ObjectInputStream inTwo=new ObjectInputStream(inOne);
table=(Hashtable)inTwo.readObject();
inOne.close();
inTwo.close();
table.put(key,日志内容);
FileOutputStream out=new FileOutputStream(file);
ObjectOutputStream objectOut=new ObjectOutputStream(out);
objectOut.writeObject(table);
objectOut.close();
out.close();
}
catch(Exception ee)
{
}
}
}
public void 删除日志(int year,int month,int day)
{
String key=""+year+""+month+""+day;
if(table.containsKey(key))
{
String m="删除"+year+"年"+month+"月"+day+"日的日志吗?";
int ok=JOptionPane.showConfirmDialog(this,m,"询问",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(ok==JOptionPane.YES_OPTION)
{
try
{
FileInputStream inOne=new FileInputStream(file);
ObjectInputStream inTwo=new ObjectInputStream(inOne);
table=(Hashtable)inTwo.readObject();
inOne.close();
inTwo.close();
table.remove(key);
FileOutputStream out=new FileOutputStream(file);
ObjectOutputStream objectOut=new ObjectOutputStream(out);
objectOut.writeObject(table);
objectOut.close();
out.close();
text.setText(null);
}
catch(Exception ee)
{
}
}
}
else
{
String m=""+year+"年"+month+"月"+day+"无日志记录";
JOptionPane.showMessageDialog(this,m,"提示",JOptionPane.WARNING_MESSAGE);
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Year extends Box implements ActionListener
{
int year;
JTextField showYear=null;
JButton 明年,去年;
CalendarPad 日历;
public Year(CalendarPad 日历)
{
super(BoxLayout.X_AXIS);
showYear=new JTextField(4);
showYear.setForeground(Color.blue);
showYear.setFont(new Font("TimesRomn",Font.BOLD,14));
this.日历=日历;
year=日历.getYear();
明年=new JButton("下年");
去年=new JButton("上年");
add(去年);
add(showYear);
add(明年);
showYear.addActionListener(this);
去年.addActionListener(this);
明年.addActionListener(this);
}
public void setYear(int year)
{
this.year=year;
showYear.setText(""+year);
}
public int getYear()
{
return year;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==去年)
{
year=year-1;
showYear.setText(""+year);
日历.setYear(year);
日历.设置日历牌(year,日历.getMonth());
}
else if(e.getSource()==明年)
{
year=year+1;
showYear.setText(""+year);
日历.setYear(year);
日历.设置日历牌(year,日历.getMonth());
}
else if(e.getSource()==showYear)
{
try
{
year=Integer.parseInt(showYear.getText());
showYear.setText(""+year);
日历.setYear(year);
日历.设置日历牌(year,日历.getMonth());
}
catch(NumberFormatException ee)
{
showYear.setText(""+year);
日历.setYear(year);
日历.设置日历牌(year,日历.getMonth());
}
}
}
}
希望能帮到你,以上分为4个类。。分割线以标注了
源代码:
//DatePicker.java
package com.kxsoft.component;
import java.awt.*;
import java.awt.event.*;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.FieldPosition;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;
public final class DatePicker extends JPanel {
private static final long serialVersionUID = 1L;
private static final int startX = 10;
private static final int startY = 60;
private static final Font smallFont = new Font("Dialog", Font.PLAIN, 10);
private static final Font largeFont = new Font("Dialog", Font.PLAIN, 12);
private static final Insets insets = new Insets(2, 2, 2, 2);
private static final Color highlight = new Color(255, 255, 204);
private static final Color white = new Color(255, 255, 255);
private static final Color gray = new Color(204, 204, 204);
private Component selectedDay = null;
private GregorianCalendar selectedDate = null;
private GregorianCalendar originalDate = null;
private boolean hideOnSelect = true;
private final JButton backButton = new JButton();
private final JLabel monthAndYear = new JLabel();
private final JButton forwardButton = new JButton();
private final JLabel[] dayHeadings = new JLabel[]{
new JLabel("日"),
new JLabel("一"),
new JLabel("二"),
new JLabel("三"),
new JLabel("四"),
new JLabel("五"),
new JLabel("六")};
private final JLabel[][] daysInMonth = new JLabel[][]{
{new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel()},
{new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel()},
{new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel()},
{new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel()},
{new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel()},
{new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel(),
new JLabel()}
};
private final JButton todayButton = new JButton();
private final JButton cancelButton = new JButton();
public DatePicker() {
super();
selectedDate = getToday();
init();
}
public DatePicker(final Date initialDate) {
super();
if (null == initialDate)
selectedDate = getToday();
else
(selectedDate = new GregorianCalendar()).setTime(initialDate);
originalDate = new GregorianCalendar(
selectedDate.get(Calendar.YEAR),
selectedDate.get(Calendar.MONTH),
selectedDate.get(Calendar.DATE));
init();
}
public boolean isHideOnSelect() {
return hideOnSelect;
}
public void setHideOnSelect(final boolean hideOnSelect) {
if (this.hideOnSelect != hideOnSelect) {
this.hideOnSelect = hideOnSelect;
initButtons(false);
}
}
public Date getDate() {
if (null != selectedDate)
return selectedDate.getTime();
return null;
}
private void init() {
setLayout(new AbsoluteLayout());
this.setMinimumSize(new Dimension(161, 226));
this.setMaximumSize(getMinimumSize());
this.setPreferredSize(getMinimumSize());
this.setBorder(new BorderUIResource.EtchedBorderUIResource());
backButton.setFont(smallFont);
backButton.setText("");
backButton.setMargin(insets);
backButton.setDefaultCapable(false);
backButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent evt) {
onBackClicked(evt);
}
});
add(backButton, new AbsoluteConstraints(10, 10, 20, 20));
monthAndYear.setFont(largeFont);
monthAndYear.setHorizontalAlignment(JTextField.CENTER);
monthAndYear.setText(formatDateText(selectedDate.getTime()));
add(monthAndYear, new AbsoluteConstraints(30, 10, 100, 20));
forwardButton.setFont(smallFont);
forwardButton.setText("");
forwardButton.setMargin(insets);
forwardButton.setDefaultCapable(false);
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent evt) {
onForwardClicked(evt);
}
});
add(forwardButton, new AbsoluteConstraints(130, 10, 20, 20));
int x = startX;
for (int ii = 0; ii dayHeadings.length; ii++) {
dayHeadings[ii].setOpaque(true);
dayHeadings[ii].setBackground(Color.LIGHT_GRAY);
dayHeadings[ii].setForeground(Color.WHITE);
dayHeadings[ii].setHorizontalAlignment(JLabel.CENTER);
add(dayHeadings[ii], new AbsoluteConstraints(x, 40, 21, 21));
x += 20;
}
x = startX;
int y = startY;
for (int ii = 0; ii daysInMonth.length; ii++) {
for (int jj = 0; jj daysInMonth[ii].length; jj++) {
daysInMonth[ii][jj].setOpaque(true);
daysInMonth[ii][jj].setBackground(white);
daysInMonth[ii][jj].setFont(smallFont);
daysInMonth[ii][jj].setHorizontalAlignment(JLabel.CENTER);
daysInMonth[ii][jj].setText("");
daysInMonth[ii][jj].addMouseListener(new MouseAdapter() {
public void mouseClicked(final MouseEvent evt) {
onDayClicked(evt);
}
});
add(daysInMonth[ii][jj], new AbsoluteConstraints(x, y, 21, 21));
x += 20;
}
x = startX;
y += 20;
}
initButtons(true);
calculateCalendar();
}
private void initButtons(final boolean firstTime) {
if (firstTime) {
final Dimension buttonSize = new Dimension(68, 24);
todayButton.setText("今天");
todayButton.setMargin(insets);
todayButton.setMaximumSize(buttonSize);
todayButton.setMinimumSize(buttonSize);
todayButton.setPreferredSize(buttonSize);
todayButton.setDefaultCapable(true);
todayButton.setSelected(true);
todayButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent evt) {
onToday(evt);
}
});
cancelButton.setText("取消");
cancelButton.setMargin(insets);
cancelButton.setMaximumSize(buttonSize);
cancelButton.setMinimumSize(buttonSize);
cancelButton.setPreferredSize(buttonSize);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent evt) {
onCancel(evt);
}
});
} else {
this.remove(todayButton);
this.remove(cancelButton);
}
类CalendarPrinter有两个主要的方法printCal()和printOut(),printCal()打印你输入年份的每一个月份,printOut()打印每一个月的每一天,在printCal()方法先创建一个格里高利历法的对象,并把你输入的年份设置为该历法的年份,然后for循环打印12个月份,然后再把每个月分别设置为你输入那年的每个月,接着调用printOut()方法打印每一天,在printOut()方法中,先获得月份,然后把日期设置为该月的第一天,接着在获取这月的第一天是一周中的周几weekday,然后打印出第一行“Sun MOn Tue Wed Thu Fri Sat”,接着就进入for循环,这个for循环就是打印每个月第一天开始前的空格,接着就进入do……while循环,获得天day,如果day10,打印day的时候day前面的空格大一些,否则day前面的空格就小一些,为了排版好看,然后判断是否是周六,如果是周六就换行,然后把day+1,重新获得新的day在一周中是周几。循环一直下去,该月的天从1一直加到30或31,再加的话月份就该+1,所以do……while循环结束的条件就是进入到下一个月。最后判断该月的最后一天是不是该月的周日,如果不是就换行
package org.java.test;
import java.util.Scanner;
public class CalendarTest{
public static void main(String[] args) {
System.out.println("欢 迎 使 用 万 年 历");
Scanner input = new Scanner(System.in);
System.out.print("\n请选择年份: ");
int year = input.nextInt();
System.out.print("\n请选择月份: ");
int month = input.nextInt();
System.out.println();
int days = 0; // 存储当月的天数
boolean isRn;
/* 判断是否是闰年 */
if (year % 4 == 0 !(year % 100 == 0) || year % 400 == 0) { // 判断是否为闰年
isRn = true; // 闰年
} else {
isRn = false;// 平年
}
/* 计算输入的年份之前的天数 */
int totalDays = 0;
for (int i = 1900; i year; i++) {
/* 判断闰年或平年,并进行天数累加 */
if (i % 4 == 0 !(i % 100 == 0) || i % 400 == 0) { // 判断是否为闰年
totalDays = totalDays + 366; // 闰年366天
} else {
totalDays = totalDays + 365; // 平年365天
}
}
/* 计算输入月份之前的天数 */
int beforeDays = 0;
for (int i = 1; i = month; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
if (isRn) {
days = 29;
} else {
days = 28;
}
break;
default:
days = 30;
break;
}
if (i month) {
beforeDays = beforeDays + days;
}
}
totalDays = totalDays + beforeDays; // 距离1900年1月1日的天数
/* 计算星期几 */
int firstDayOfMonth; // 存储当月第一天是星期几:星期日为0,星期一~星期六为1~6
int temp = 1 + totalDays % 7; // 从1900年1月1日推算
if (temp == 7) { // 求当月第一天
firstDayOfMonth = 0; // 周日
} else {
firstDayOfMonth = temp;
}
/* 输出日历 */
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for (int nullNo = 0; nullNo firstDayOfMonth; nullNo++) {
System.out.print("\t"); // 输出空格
}
for (int i = 1; i = days; i++) {
System.out.print(i + "\t");
if ((totalDays + i-1) % 7 == 5) { // 如果当天为周六,输出换行
System.out.println();
}
}
}
}
这是你要的万年历吗?
也不知道你具体需求是什么,以前改过一个日历程序,一共四个java类,放在同一个包里。经测试可以运行。
//Start.java
import java.awt.*;
import javax.swing.*;
class Start{
public static void main(String [] args){
DateFrame frame=new DateFrame();
frame.setLocationRelativeTo(frame);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//DateInfo.java
import java.util.*;
public class DateInfo{
private int mYear, mMonth;
private int mDayOfMonth, mFristWeek;
public DateInfo(int year, int month) throws DateException{
mYear = year;
if (month 0 || month 12){
throw (new DateException());
}
mMonth = month;
mDayOfMonth = getDayOfMonth(mYear, mMonth);
mFristWeek = getFristWeek(mYear, mMonth);
}
private int getDayOfMonth(int year, int month){
int[][] ary = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
return (ary[isLeapYear(year)][month]);
}
private int isLeapYear(int year){
if (year % 4 == 0 year % 100 != 0 ||year % 400 == 0){
return (1);
}
else{
return (0);
}
}
private int getFristWeek(int year, int month){
java.util.Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
return (cal.get(Calendar.DAY_OF_WEEK) - 1);
}
public String toString(){
String str;
str = "\t\t" + mYear + "年" + mMonth + "月\n";
str += "日\t一\t二\t三\t四\t五\t六\n";
int i;
for (i = 1; i = mFristWeek; i++){
str += " \t";
}
for (int j = 1; j = mDayOfMonth; j++, i++){
str +=j+"\t" ;
if (i % 7 == 0){
str += "\n";
}
}
return (str);
}
}
//DateFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;
class DateFrame extends JFrame implements Runnable{
Calendar date=Calendar.getInstance();
String[] str={"1","2","3","4","5","6","7","8","9","10","11","12"};
JLabel lblYear=new JLabel("年 ");
JLabel lblMonth=new JLabel("月 ");
JLabel lblDate=new JLabel("现在的时间是:");
JLabel lblShowDate=new JLabel();
// javax.swing.JTextField trxt =new JTextField(10);
// trxt.setHorizontalAlignment(JTextField.RIGHT); //设置文本从右边输入
JComboBox cboMonth=new JComboBox(str);
JComboBox cboYear=new JComboBox();
JTextArea txaShow=new JTextArea();
JPanel pnlNorth=new JPanel();
JPanel pnlSOUTH=new JPanel();
JButton btnShow=new JButton("显示");
JButton btnClose=new JButton("关闭");
JScrollPane jsp=new JScrollPane(txaShow);
Container c=this.getContentPane();
public DateFrame(){
Thread thread=new Thread(this);
thread.start();
this.setTitle("玩玩日历拉!!!");
this.setSize(300,260);
for (int i = 1990; i=2025; i++) {
cboYear.addItem(""+i);
}
cboYear.setSelectedItem(""+(date.get(Calendar.YEAR)));
cboMonth.setSelectedItem(""+(date.get(Calendar.MONTH)+1));
pnlNorth.add(cboYear);
txaShow.setTabSize(4); //设置tab键的距离
txaShow.setForeground(Color.GREEN);
pnlNorth.add(lblYear);
pnlNorth.add(cboMonth);
pnlNorth.add(lblMonth);
pnlNorth.add(lblDate);
pnlNorth.add(lblShowDate);
c.add(pnlNorth,BorderLayout.NORTH);
c.add(jsp);
pnlSOUTH.add(btnShow);
pnlSOUTH.add(btnClose);
c.add(pnlSOUTH,BorderLayout.SOUTH);
btnShow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int year=Integer.parseInt((String)cboYear.getSelectedItem());
int month=Integer.parseInt((String)cboMonth.getSelectedItem());
try {
DateInfo date=new DateInfo(year,month);
txaShow.setText(""+date);
}
catch (DateException ex) {
ex.printStackTrace();
}
}
});
btnClose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public void run(){
try {
while(true){
Thread.sleep(1000);
int hour=date.get(Calendar.HOUR);
int minute=date.get(Calendar.MINUTE);
int second=date.get(Calendar.SECOND);
String str=hour+":"+minute+":"+second;
lblShowDate.setText(str);
//this.repaint();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//DateException.java
public class DateException extends Exception{
public DateException(){
super("日期数据不合法.");
}
}
/**
* @(#) MyCalendar.java
* @author fancy
*/
//日历使用的类
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
//日历
public class MyCalendar extends JApplet
{
public static final String WEEK_SUN = "SUN";
public static final String WEEK_MON = "MON";
public static final String WEEK_TUE = "TUE";
public static final String WEEK_WED = "WED";
public static final String WEEK_THU = "THU";
public static final String WEEK_FRI = "FRI";
public static final String WEEK_SAT = "SAT";
public static final Color background = Color.yellow;
public static final Color foreground = Color.black;
public static final Color headerBackground = Color.blue;
public static final Color headerForeground = Color.white;
public static final Color selectedBackground = Color.blue;
public static final Color selectedForeground = Color.white;
private JPanel cPane;
private JLabel yearsLabel;
private JSpinner yearsSpinner;
private JLabel monthsLabel;
private JComboBox monthsComboBox;
private JTable daysTable;
private AbstractTableModel daysModel;
private Calendar calendar;
private JTextField time1;
public MyCalendar() {
cPane = (JPanel) getContentPane();
}
public void init() {
cPane.setLayout(new BorderLayout());
calendar = Calendar.getInstance();
time1 = new JTextField();
Thread t = new Thread(){
public void run()
{
while(true)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
time1.setText("当前时间是: "+sdf.format(new Date()));
try
{
Thread.sleep(1000);
}catch(Exception e)
{}
}
}
};
cPane.add(time1,BorderLayout.SOUTH);
t.start();
yearsLabel = new JLabel("Year: ");
yearsSpinner = new JSpinner();
yearsSpinner.setEditor(new JSpinner.NumberEditor(yearsSpinner, "0000"));
yearsSpinner.setValue(new Integer(calendar.get(Calendar.YEAR)));
yearsSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.YEAR, ((Integer) yearsSpinner.getValue()).intValue());
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, day maxDay ? maxDay : day);
updateView();
}
});
JPanel yearMonthPanel = new JPanel();
cPane.add(yearMonthPanel, BorderLayout.NORTH);
yearMonthPanel.setLayout(new BorderLayout());
yearMonthPanel.add(new JPanel(), BorderLayout.CENTER);
JPanel yearPanel = new JPanel();
yearMonthPanel.add(yearPanel, BorderLayout.WEST);
yearPanel.setLayout(new BorderLayout());
yearPanel.add(yearsLabel, BorderLayout.WEST);
yearPanel.add(yearsSpinner, BorderLayout.CENTER);
monthsLabel = new JLabel("Month: ");
monthsComboBox = new JComboBox();
for (int i = 1; i = 12; i++) {
monthsComboBox.addItem(new Integer(i));
}
monthsComboBox.setSelectedIndex(calendar.get(Calendar.MONTH));
monthsComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, monthsComboBox.getSelectedIndex());
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, day maxDay ? maxDay : day);
updateView();
}
});
JPanel monthPanel = new JPanel();
yearMonthPanel.add(monthPanel, BorderLayout.EAST);
monthPanel.setLayout(new BorderLayout());
monthPanel.add(monthsLabel, BorderLayout.WEST);
monthPanel.add(monthsComboBox, BorderLayout.CENTER);
daysModel = new AbstractTableModel() {
public int getRowCount() {
return 9;
}
public int getColumnCount() {
return 7;
}
public Object getValueAt(int row, int column) {
if (row == 0) {
return getHeader(column);
}
row--;
Calendar calendar = (Calendar) MyCalendar.this.calendar.clone();
calendar.set(Calendar.DAY_OF_MONTH, 1);
int dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int moreDayCount = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int index = row * 7 + column;
int dayIndex = index - moreDayCount + 1;
if (index moreDayCount || dayIndex dayCount) {
return null;
} else {
return new Integer(dayIndex);
}
}
};
daysTable = new CalendarTable(daysModel, calendar);
daysTable.setCellSelectionEnabled(true);
daysTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
daysTable.setDefaultRenderer(daysTable.getColumnClass(0), new TableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
String text = (value == null) ? "" : value.toString();
JLabel cell = new JLabel(text);
cell.setOpaque(true);
if (row == 0) {
cell.setForeground(headerForeground);
cell.setBackground(headerBackground);
} else {
if (isSelected) {
cell.setForeground(selectedForeground);
cell.setBackground(selectedBackground);
} else {
cell.setForeground(foreground);
cell.setBackground(background);
}
}
if(column == 0)
{
cell.setForeground(Color.red);
}
return cell;
}
});
updateView();
cPane.add(daysTable, BorderLayout.CENTER);
}
public static String getHeader(int index) {
switch (index) {
case 0:
return WEEK_SUN;
case 1:
return WEEK_MON;
case 2:
return WEEK_TUE;
case 3:
return WEEK_WED;
case 4:
return WEEK_THU;
case 5:
return WEEK_FRI;
case 6:
return WEEK_SAT;
default:
return null;
}
}
public void updateView() {
daysModel.fireTableDataChanged();
daysTable.setRowSelectionInterval(calendar.get(Calendar.WEEK_OF_MONTH),
calendar.get(Calendar.WEEK_OF_MONTH));
daysTable.setColumnSelectionInterval(calendar.get(Calendar.DAY_OF_WEEK) - 1,
calendar.get(Calendar.DAY_OF_WEEK) - 1);
}
public static class CalendarTable extends JTable {
private Calendar calendar;
public CalendarTable(TableModel model, Calendar calendar) {
super(model);
this.calendar = calendar;
}
public void changeSelection(int row, int column, boolean toggle, boolean extend) {
super.changeSelection(row, column, toggle, extend);
if (row == 0) {
return;
}
Object obj = getValueAt(row, column);
if (obj != null) {
calendar.set(Calendar.DAY_OF_MONTH, ((Integer)obj).intValue());
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("简易时间日历");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyCalendar myCalendar = new MyCalendar();
myCalendar.init();
frame.getContentPane().add(myCalendar);
frame.setLocation(330,80);
frame.setSize(360, 212);
frame.setVisible(true);
}
}