用Java实现的日历程序如下(图形界面程序)
十载的潮阳网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都营销网站建设的优势是能够根据用户设备显示端的尺寸不同,自动调整潮阳建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联建站从事“潮阳网站设计”,“潮阳网站推广”以来,每个客户项目都认真落实执行。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CCI extends JFrame implements ActionListener{
JButton jb1=new JButton("");
JButton jb2=new JButton("");
JButton jb3=new JButton("");
JButton jb4=new JButton("");
JPanel jp1=new JPanel();
JPanel jp2=new JPanel();
JPanel jp3=new JPanel();
JPanel jp4=new JPanel();
JLabel jl1=new JLabel();
JLabel jl2=new JLabel();
JLabel[]jl=new JLabel[49];
String []week={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
Calendar c=Calendar.getInstance();
int year,month,day;
int nowyear,nowmonth,nowday;
CCI(){
super("简单日历");
nowyear=c.get(Calendar.YEAR);
nowmonth=c.get(Calendar.MONTH)+1;
nowday=c.get(Calendar.DAY_OF_MONTH);
year=nowyear;
month=nowmonth;
day=nowday;
String s=year+"年"+month+"月";
jl1.setForeground(Color.RED);
jl1.setFont(new Font(null,Font.BOLD,20));
jl1.setText(s);
jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);
jb4.addActionListener(this);
jp1.add(jb1);jp1.add(jb2);jp1.add(jl1);jp1.add(jb3);jp1.add(jb4);
jp2.setLayout(null);
createMonthPanel();
jp2.add(jp3);
jl2.setFont(new Font(null,Font.BOLD,20));
jl2.setText("今天是"+nowyear+"年"+nowmonth+"月"+nowday+"日");
jp4.add(jl2);
add(jp1,BorderLayout.NORTH);
add(jp2,BorderLayout.CENTER);
add(jp4,BorderLayout.SOUTH);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==jb1){
year=year-1;
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
if(ae.getSource()==jb2){
if(month==1){
year=year-1;
month=12;
}else{
month=month-1;
}
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
if(ae.getSource()==jb3){
if(month==12){
year=year+1;
month=1;
}else{
month=month+1;
}
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
if(ae.getSource()==jb4){
year=year+1;
String s=year+"年"+month+"月";
jl1.setText(s);
jp3.removeAll();
createMonthPanel();
jp3.validate();
}
}
public static void main(String[] args) {
new CCI();
}
public int getMonthDays(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
if ((year%4==0year%100!=0)||year%400==0) {
return 29;
} else {
return 28;
}
default:
return 30;
}
}
public void createMonthPanel(){
c.set(year, month-1, getMonthDays(year,month));
int weekOfMonth=c.get(Calendar.WEEK_OF_MONTH);
if(weekOfMonth==6){
jp3.setLayout(new GridLayout(7,7));
jp3.setBounds(50, 20, 420, 350);
}else{
jp3.setLayout(new GridLayout(6,7));
jp3.setBounds(50, 20, 420, 300);
}
jp3.setBorder(BorderFactory.createEtchedBorder());
for(int i=0;i7;i++){
jl[i]=new JLabel(week[i],JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
c.set(year, month-1, 1);
int emptyFirst=c.get(Calendar.DAY_OF_WEEK)-1;
int daysOfMonth=getMonthDays(year,month);
for(int i=6+emptyFirst;i=7;i--){
int intyear=year;
int intmonth=month;
if(intmonth==1){
intyear=intyear-1;
intmonth=12;
}else{
intmonth=intmonth-1;
}
int intdays=getMonthDays(intyear,intmonth);
jl[i]=new JLabel((intdays+7-i)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setForeground(Color.GRAY);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
for(int i=7+emptyFirst;idaysOfMonth+7+emptyFirst;i++){
jl[i]=new JLabel((i-7-emptyFirst+1)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
if((i+1)%7==0 || (i+1)%7==1){
jl[i].setForeground(Color.RED);
}else if((i-7-emptyFirst+1)==nowdaymonth==nowmonthyear==nowyear)
jl[i].setForeground(Color.BLUE);
else
jl[i].setForeground(Color.BLACK);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
if(weekOfMonth==6)
for(int i=48;i=daysOfMonth+emptyFirst+7;i--){
jl[i]=new JLabel((49-i)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setForeground(Color.GRAY);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
else
for(int i=41;i=daysOfMonth+emptyFirst+7;i--){
jl[i]=new JLabel((42-i)+"",JLabel.CENTER);
jl[i].setFont(new Font(null,Font.BOLD,20));
jl[i].setForeground(Color.GRAY);
jl[i].setBorder(BorderFactory.createEtchedBorder());
jp3.add(jl[i]);
}
}
}
运行结果
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Date;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
/**
* pTitle: Swing日历/p
* pDescription: 操作日期/p
* @author duxu2004
* @version 1.0.1
*/
class JCalendar extends JPanel{
//动态表示年月日
private int year=0;
private int month=0;
private int day=0;
//主面板
private JPanel Main = new JPanel();
//日面板
private JPanel jPanelDay = new JPanel();
//月面板
private JPanel jPanelMonth = new JPanel();
//年的输入位置
private JTextField Year = new JTextField();
//月的输入位置
private JTextField Month = new JTextField();
//减少月份
private JButton MonthDown = new JButton();
//增加月份
private JButton MonthUp = new JButton();
private JPanel jPanelButton = new JPanel();
//减少年份
private JButton YearDown = new JButton();
//增加年份
private JButton YearUp = new JButton();
//显示日期的位置
private JLabel Out = new JLabel();
//中国时区,以后可以从这里扩展可以设置时区的功能
private Locale l=Locale.CHINESE;
//主日历
private GregorianCalendar cal=new GregorianCalendar(l);
//星期面板
private JPanel weekPanel=new JPanel();
//天按钮组
private JToggleButton[] days=new JToggleButton[42];
//天面板
private JPanel Days = new JPanel();
//标示
private JLabel jLabel1 = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JLabel jLabel4 = new JLabel();
private JLabel jLabel5 = new JLabel();
private JLabel jLabel6 = new JLabel();
private JLabel jLabel7 = new JLabel();
//当前选择的天数按钮
private JToggleButton cur=null;
//月份天数数组,用来取得当月有多少天
// 1 2 3 4 5 6 7 8 9 10 11 12
private int[] mm={31,28,31,30,31,30,31,31,30,31,30,31};
//空日期构造函数
public JCalendar() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
//带日期设置的构造函数
public JCalendar(int year, int month, int day) {
cal.set(year, month, day);
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
//带日历输入的构造函数
public JCalendar(GregorianCalendar calendar) {
cal=calendar;
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
//带日期输入的构造函数
public JCalendar(Date date) {
cal.setTime(date);
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
//初始化组件
private void jbInit() throws Exception {
//初始化年、月、日
iniCalender();
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createRaisedBevelBorder());
this.setMaximumSize(new Dimension(200, 200));
this.setMinimumSize(new Dimension(200, 200));
this.setPreferredSize(new Dimension(200, 200));
Main.setLayout(new BorderLayout());
Main.setBackground(SystemColor.info);
Main.setBorder(null);
Out.setBackground(Color.lightGray);
Out.setHorizontalAlignment(SwingConstants.CENTER);
Out.setMaximumSize(new Dimension(100, 19));
Out.setMinimumSize(new Dimension(100, 19));
Out.setPreferredSize(new Dimension(100, 19));
jLabel1.setForeground(Color.red);
jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
jLabel1.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel1.setText("日");
jLabel2.setForeground(Color.blue);
jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
jLabel2.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel2.setText("六");
jLabel3.setHorizontalAlignment(SwingConstants.CENTER);
jLabel3.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel3.setText("五");
jLabel4.setHorizontalAlignment(SwingConstants.CENTER);
jLabel4.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel4.setText("四");
jLabel5.setHorizontalAlignment(SwingConstants.CENTER);
jLabel5.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel5.setText("三");
jLabel6.setBorder(null);
jLabel6.setHorizontalAlignment(SwingConstants.CENTER);
jLabel6.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel6.setText("二");
jLabel7.setBackground(Color.lightGray);
jLabel7.setForeground(Color.black);
jLabel7.setBorder(null);
jLabel7.setHorizontalAlignment(SwingConstants.CENTER);
jLabel7.setHorizontalTextPosition(SwingConstants.CENTER);
jLabel7.setText("一");
weekPanel.setBackground(UIManager.getColor("InternalFrame.activeTitleGradient"));
weekPanel.setBorder(BorderFactory.createEtchedBorder());
weekPanel.setLayout(new GridLayout(1,7));
weekPanel.add(jLabel1, null);
weekPanel.add(jLabel7, null);
weekPanel.add(jLabel6, null);
weekPanel.add(jLabel5, null);
weekPanel.add(jLabel4, null);
weekPanel.add(jLabel3, null);
weekPanel.add(jLabel2, null);
MonthUp.setAlignmentX((float) 0.0);
MonthUp.setActionMap(null);
jPanelMonth.setBackground(SystemColor.info);
jPanelMonth.setLayout(new BorderLayout());
jPanelMonth.setBorder(BorderFactory.createEtchedBorder());
Month.setBorder(null);
Month.setHorizontalAlignment(SwingConstants.CENTER);
Month.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Month_mouseClicked(e);
}
});
Month.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e) {
Month_keyPressed(e);
}
});
MonthDown.setBorder(null);
MonthDown.setText("\u25C4");
MonthDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
MonthDown_actionPerformed(e);
}
});
MonthUp.setBorder(null);
MonthUp.setText("\u25BA");
MonthUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
MonthUp_actionPerformed(e);
}
});
jPanelButton.setLayout(null);
jPanelButton.setBorder(null);
jPanelButton.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
jPanelButtonComponentResized(evt);
}
});
Year.setBorder(BorderFactory.createEtchedBorder());
Year.setMaximumSize(new Dimension(80, 25));
Year.setMinimumSize(new Dimension(80, 25));
Year.setPreferredSize(new Dimension(80, 25));
Year.setHorizontalAlignment(SwingConstants.CENTER);
Year.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Year_mouseClicked(e);
}
});
Year.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e) {
Year_keyPressed(e);
}
});
YearDown.setBorder(null);
YearDown.setMaximumSize(new Dimension(16, 16));
YearDown.setMinimumSize(new Dimension(16, 16));
YearDown.setPreferredSize(new Dimension(16, 16));
YearDown.setSize(new Dimension(16, 16));
YearDown.setText("▼");
YearDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
YearDown_actionPerformed(e);
}
});
YearUp.setBorder(null);
YearUp.setMaximumSize(new Dimension(16, 16));
YearUp.setMinimumSize(new Dimension(16, 16));
YearUp.setPreferredSize(new Dimension(16, 16));
YearUp.setSize(new Dimension(16, 16));
YearUp.setText("▲");
YearUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
YearUp_actionPerformed(e);
}
});
jPanelDay.setLayout(new BorderLayout());
Days.setLayout(new GridLayout(6,7));
Days.setBackground(SystemColor.info);
for(int i=0;i42;i++){
days[i]=new JToggleButton();
days[i].setBorder(null);
days[i].setBackground(SystemColor.info);
days[i].setHorizontalAlignment(SwingConstants.CENTER);
days[i].setHorizontalTextPosition(SwingConstants.CENTER);
//days[i].setSize(l,l);
days[i].addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(ActionEvent e) {
day=Integer.parseInt(((JToggleButton)e.getSource()).getText());
showDate();
showDays();
}
});
Days.add(days[i]);
}
this.add(Main, BorderLayout.NORTH);
this.add(jPanelDay, BorderLayout.CENTER);
this.add(jPanelMonth, BorderLayout.SOUTH);
Main.add(Year, BorderLayout.CENTER);
Main.add(Out, BorderLayout.WEST);
Main.add(jPanelButton, BorderLayout.EAST);
jPanelButton.add(YearUp);
jPanelButton.add(YearDown);
jPanelDay.add(weekPanel,BorderLayout.NORTH);
jPanelDay.add(Days, BorderLayout.CENTER);
jPanelMonth.add(Month, BorderLayout.CENTER);
jPanelMonth.add(MonthDown, BorderLayout.WEST);
jPanelMonth.add(MonthUp, BorderLayout.EAST);
showMonth();
showYear();
showDate();
showDays();
}
//自定义重画年选择面板
void jPanelButtonComponentResized(java.awt.event.ComponentEvent evt){
YearUp.setLocation(0,0);
YearDown.setLocation(0,YearUp.getHeight());
jPanelButton.setSize(YearUp.getWidth(),YearUp.getHeight()*2);
jPanelButton.setPreferredSize(new Dimension(YearUp.getWidth(),YearUp.getHeight()*2));
jPanelButton.updateUI();
}
//测试用
public static void main(String[] args){
JFrame f=new JFrame();
f.setContentPane(new JCalendar());
f.pack();
//f.setResizable(false);
f.show();
}
//增加年份
void YearUp_actionPerformed(ActionEvent e) {
year++;
showYear();
showDate();
showDays();
}
//减少年份
void YearDown_actionPerformed(ActionEvent e) {
year--;
showYear();
showDate();
showDays();
}
//减少月份
void MonthDown_actionPerformed(ActionEvent e) {
month--;
if(month0) {
month = 11;
year--;
showYear();
}
showMonth();
showDate();
showDays();
}
//增加月份
void MonthUp_actionPerformed(ActionEvent e) {
month++;
if(month==12) {
month=0;
year++;
showYear();
}
showMonth();
showDate();
showDays();
}
//初始化年月日
void iniCalender(){
year=cal.get(Calendar.YEAR);
month=cal.get(Calendar.MONTH);
day=cal.get(Calendar.DAY_OF_MONTH);
}
//刷新月份
void showMonth(){
Month.setText(Integer.toString(month+1)+"月");
}
//刷新年份
void showYear(){
Year.setText(Integer.toString(year)+"年");
}
//刷新日期
void showDate(){
Out.setText(Integer.toString(year)+"-"+Integer.toString(month+1)+"-"+Integer.toString(day));
}
//重画天数选择面板
void showDays() {
cal.set(year,month,1);
int firstDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int n=mm[month];
if(cal.isLeapYear(year)month==1) n++;
int i=0;
for(;ifirstDayOfWeek-1;i++){
days[i].setEnabled(false);
days[i].setSelected(false);
days[i].setText("");
}
int d=1;
for(;d=n;d++){
days[i].setText(Integer.toString(d));
days[i].setEnabled(true);
if(d==day) days[i].setSelected(true);
else days[i].setSelected(false);;
i++;
}
for(;i42;i++){
days[i].setEnabled(false);
days[i].setSelected(false);
days[i].setText("");
}
}
//单击年份面板选择整个年份字符串
void SelectionYear(){
Year.setSelectionStart(0);
Year.setSelectionEnd(Year.getText().length());
}
//单击月份面板选择整个月份字符串
void SelectionMonth(){
Month.setSelectionStart(0);
Month.setSelectionEnd(Month.getText().length());
}
//月份面板响应鼠标单击事件
void Month_mouseClicked(MouseEvent e) {
//SelectionMonth();
inputMonth();
}
//检验输入的月份
void inputMonth(){
String s;
if(Month.getText().endsWith("月"))
{
s=Month.getText().substring(0,Month.getText().length()-1);
}
else s=Month.getText();
month=Integer.parseInt(s)-1;
this.showMe();
}
//月份面板键盘敲击事件响应
void Month_keyPressed(KeyEvent e) {
if(e.getKeyChar()==10)
inputMonth();
}
//年份面板响应鼠标单击事件
void Year_mouseClicked(MouseEvent e) {
//SelectionYear();
inputYear();
}
//年份键盘敲击事件响应
void Year_keyPressed(KeyEvent e) {
//System.out.print(new Integer(e.getKeyChar()).byteValue());
if(e.getKeyChar()==10)
inputYear();
}
//检验输入的年份字符串
void inputYear() {
String s;
if(Year.getText().endsWith("年"))
{
s=Year.getText().substring(0,Year.getText().length()-1);
}
else s=Year.getText();
year=Integer.parseInt(s);
this.showMe();
}
//以字符串形式返回日期,yyyy-mm-dd
public String getDate(){return Out.getText();}
//以字符串形式输入日期,yyyy-mm-dd
public void setDate(String date){
if(date!=null){
StringTokenizer f = new StringTokenizer(date, "-");
if(f.hasMoreTokens())
year = Integer.parseInt(f.nextToken());
if(f.hasMoreTokens())
month = Integer.parseInt(f.nextToken());
if(f.hasMoreTokens())
day = Integer.parseInt(f.nextToken());
cal.set(year,month,day);
}
this.showMe();
}
//以日期对象形式输入日期
public void setTime(Date date){
cal.setTime(date);
this.iniCalender();
this.showMe();
}
//返回日期对象
public Date getTime(){return cal.getTime();}
//返回当前的日
public int getDay() {
return day;
}
//设置当前的日
public void setDay(int day) {
this.day = day;
cal.set(this.year,this.month,this.day);
this.showMe();
}
//设置当前的年
public void setYear(int year) {
this.year = year;
cal.set(this.year,this.month,this.day);
this.showMe();
}
//返回当前的年
public int getYear() {
return year;
}
//返回当前的月
public int getMonth() {
return month;
}
//设置当前的月
public void setMonth(int month) {
this.month = month;
cal.set(this.year,this.month,this.day);
this.showMe();
}
//刷新
public void showMe(){
this.showDays();
this.showMonth();
this.showYear();
this.showDate();
}
}
public class TestJCalendar {
public static void main(String[] args) {
JFrame f=new JFrame();
f.setContentPane(new JCalendar());
f.pack();
//f.setResizable(false);
f.show();
}
}
import java.util.Scanner; public class Wan{ public static void main(String[] args){ Scanner name = new Scanner(System.in); System.out.print("请输入要查询的年份:"); int year = name.nextInt(); System.out.print("请输入该年的月份"); int month = name.nextInt(); } //累加 该年至输入的月份 天数 //比如 输入2009年的 3月分 // 那就累加 2009年的1月至 3月1号的总天数 public void sumDay(int year,int month){ int day = 0; int sumDay = 0; for(int i = 1;i=month;i++){ switch(i){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 2: if(year % 4 == 0 || year % 400 == 0 year %100!=0){ day = 29; }else{ day = 28; } break; default: day = 30; } //最后一个月份不要累加 因为我们只是要算到该月的一号就可以了 if(i month){ sumDay += day; } } //累加 2000年到该年的一月一号天数 for(int i = 2000;iyear;i++){ if( i % 4 == 0 || i %400== 0 i % 100 != 0){ sumDay += 366; }else{ sumDay += 365; } } //求该月一号为星期几 int week = sumDay % 7 +1; if(week == 7){ week = 0; } } public void fomatDate(int week,int day){ int g = 0; for(int i = 0;iweek;i++){ System.out.print("\t"); } for(int i = 1;i=day;i++){ System.out.print(i+"\t"); g = week + i; if(g % 7 == 0){ System.out.println(); } } } } 给点分哈 写得好累
随便做了一个,其实一楼网友说的判断哪些30天,是否闰年什么的没必要,看代码:
package com.baidu.calendar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CalendarInterface extends JFrame {
private static final long serialVersionUID = 1L;
private JComboBox yearBox, monthBox;
private static final int YEAR_RANGE = 50; // 年份范围,即往前往后各推多少年
private JPanel topPane, contentPane;
private JPanel bottomPane, bottomTopPane, mainPane;
private JLabel dateLabel;
private boolean init = false;
private Calendar cal;
private static final Calendar NOW = Calendar.getInstance();
private static final String[] DAY_OF_WEEK = {"星期日", "星期一", "星期二",
"星期三", "星期四", "星期五", "星期六"};
private DateFormat df = new SimpleDateFormat("yyyy年MM月");
private static final Color FONT_GRAY = new Color(0xaa, 0xaa, 0xaa);
private static final int DATE_GRAY = -1;
private static final int DATE_RED = 1;
private static final int DATE_BLACK = 0;
public CalendarInterface() {
super("日历");
cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
}
public void launch() {
setVisible(true);
setSize(600, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 主面板
contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setBackground(Color.WHITE);
// 顶部选择日期和月份的区域
topPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 0)); // 居中对齐,控件间隔50px
topPane.setBorder(new EmptyBorder(0, 0, 10, 0)); // 底部空出10px
topPane.setBackground(Color.WHITE);
// 底部显示星期条和日历列表区域
bottomPane = new JPanel(new BorderLayout());
bottomPane.setBorder(new LineBorder(Color.BLACK, 1));
// 星期条
bottomTopPane = new JPanel(new GridLayout(1, 7));
bottomTopPane.setBackground(new Color(0x55, 0x55, 0x55));
// 日期列表
mainPane = new JPanel();
mainPane.setLayout(new GridLayout(0, 7)); // 列数为7,行数自动填充
for(int i = Calendar.SUNDAY; i = Calendar.SATURDAY; i ++) {
bottomTopPane.add(createDay(DAY_OF_WEEK[i - 1]));
}
bottomPane.add(bottomTopPane, BorderLayout.NORTH); // 星期栏放在顶部
// 年份下拉列表
yearBox = new JComboBox();
int currentYear = cal.get(Calendar.YEAR);
// 年份范围为往前往后各推50年
for(int i = currentYear - YEAR_RANGE; i currentYear + YEAR_RANGE + 1; i ++) {
yearBox.addItem(i);
}
yearBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(ItemEvent.SELECTED == e.getStateChange()) {
reset(); // 选择后刷新布局
}
}
});
yearBox.setSelectedIndex(YEAR_RANGE); // 默认选中当前年份
String months[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
// 月份下拉列表
monthBox = new JComboBox(months);
monthBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(ItemEvent.SELECTED == e.getStateChange()) {
reset(); //刷新布局
}
}
});
monthBox.setSelectedIndex(cal.get(Calendar.MONTH)); // 选择当前月份
// 显示当前年月的控件
this.dateLabel = new JLabel(df.format(cal.getTime()));
topPane.add(yearBox);
topPane.add(monthBox);
topPane.add(dateLabel);
contentPane.add(topPane, BorderLayout.NORTH);
bottomPane.add(mainPane, BorderLayout.CENTER);
contentPane.add(bottomPane, BorderLayout.CENTER);
setContentPane(contentPane);
validate();
init = true; // 初始化完成
reset(); // 刷新界面
setLocationRelativeTo(null); // 居中显示
}
public static void main(String[] args) {
new CalendarInterface().launch();
}
private void reset() { // 每次年份或月份改变后则日历重新排列
if(!init) { // 若未初始化则返回,避免设置默认年月时调用此方法出错
return;
}
int year = (Integer) yearBox.getSelectedItem();
int month = Integer.parseInt((String) monthBox.getSelectedItem());
// 将日期设置为本月第一天
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DATE, 1);
dateLabel.setText(df.format(cal.getTime())); // 显示年月
mainPane.removeAll(); // 清空日历列表
// 判断本月第一天是星期几,在第一天之前增加空的日历
int startDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int i;
// 先设置为本周属于上个月的几天,置灰显示
cal.add(Calendar.DATE, -(startDayOfWeek - Calendar.SUNDAY) - 1);
for(i = Calendar.SUNDAY; i startDayOfWeek; i ++) {
cal.add(Calendar.DATE, 1);
int date = cal.get(Calendar.DATE);
mainPane.add(createDate(Integer.toString(date), DATE_GRAY));
}
i = startDayOfWeek;
// 重新初始化为本月第一天
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DATE, 1);
int maxDate = cal.getActualMaximum(Calendar.DATE); // 本月最多的天数(不用再去判断是否闰年了)
for(int j = 1; j = maxDate; j ++) {
cal.set(Calendar.DATE, j); // 日期一直自增,用来判断是否是今天
JLabel jlDate = null;
if(isToday()) { // 是今天则高亮显示
jlDate = createDate(Integer.toString(j), DATE_RED);
} else { // 不是今天则显示为普通颜色
jlDate = createDate(Integer.toString(j));
}
mainPane.add(jlDate);
}
// 最后一周把不属于本月的几天用灰色控件填充
int lastDay = cal.get(Calendar.DAY_OF_WEEK);
for(i = lastDay; i Calendar.SATURDAY; i ++) {
cal.add(Calendar.DATE, 1);
int date = cal.get(Calendar.DATE);
mainPane.add(createDate(Integer.toString(date), DATE_GRAY));
}
mainPane.validate();
}
private JLabel createDate(String date) {
return createDate(date, DATE_BLACK);
}
// 创建日期控件
private JLabel createDate(String date, int dateColor) {
JLabel label = new JLabel(date, JLabel.CENTER);
CompoundBorder border = new CompoundBorder(
new LineBorder(Color.WHITE, 1),
new EmptyBorder(10, 10, 10, 10));
label.setBorder(border);
Font font = new Font("Arial", Font.BOLD, 30);
if(DATE_GRAY == dateColor) { // 如果不是本月则文字置灰
label.setForeground(FONT_GRAY);
} else if(DATE_RED == dateColor) { // 如果是今天则高亮显示
label.setForeground(Color.RED);
}
label.setFont(font);
return label;
}
// 创建星期几的横条
private JLabel createDay(String day) {
JLabel jlDay = new JLabel(day, JLabel.CENTER);
jlDay.setBorder(new EmptyBorder(5, 5, 5, 5));
jlDay.setBackground(Color.GRAY);
jlDay.setForeground(Color.WHITE);
return jlDay;
}
// 判断是否今天
private boolean isToday() {
return cal.get(Calendar.YEAR) == NOW.get(Calendar.YEAR)
cal.get(Calendar.MONTH) == NOW.get(Calendar.MONTH)
cal.get(Calendar.DATE) == NOW.get(Calendar.DATE);
}
}
我给你贴上我在java核心技术中看到的代码吧,当然没有输入年份和月份,是按照当前时间创建的,写有我写的注释,应该能看的懂
/*
* 2012年5月13日10:37:58
* 日历程序
* Function:
* 显示当前月份的日历
* 总结
* 1. 0-11分别代表1-12月
* 1-7分别代表周日-周六
* 2. 使用GregorianCalendar对象的get方法(参数)获取月,日,年等信息
* 3.
*/
import java.text.DateFormatSymbols;
import java.util.*;
public class CalendarTest {
public static void main(String[] args) {
//construct d as current date构造一个日期
GregorianCalendar d = new GregorianCalendar();
//获取今天是这个月的第几天
int today = d.get(Calendar.DAY_OF_MONTH); //Calendar.DAY_OF_MONTH作为参数调用,得到今天是这个月的第几天
int month = d.get(Calendar.MONTH); //月份
d.set(Calendar.DAY_OF_MONTH, 1); //设置d的日期是本月的1号
int weekDay = d.get(Calendar.DAY_OF_WEEK); //获取当天位于本星期的第几天,也就确定了星期几,值的范围是1-7
int firstDayOfWeek = d.getFirstDayOfWeek(); //获取一星期的第一天,我们得到的是Calendar.SUNDAY,因为我们一星期的第一天是周日
int indent = 0; //为了定位本月第一天,定义索引
while (weekDay != firstDayOfWeek) {
//注意,月份用0-11代表1-12月,为了清晰起见,使用常量代替,下面获取月份得到的实际是当前月-1的值,所以我们要加1
//System.out.printf("当前星期的第%d天,位于当月的第%d天, 现在是%d月\n",
// weekDay, d.get(Calendar.DAY_OF_MONTH), d.get(Calendar.MONTH)+1); //Test Code
indent++;//缩进个数+1
d.add(Calendar.DAY_OF_MONTH, -1);//当前天数-1,如果现在是1号,则执行本条代码后,时间变为上一个月最后一天
weekDay = d.get(Calendar.DAY_OF_WEEK); //重新获取当天位于本星期的第几天
}
String[] weekDayNames = new DateFormatSymbols().getShortWeekdays();//获取简短形式的星期字符串数组
//System.out.println(weekDayNames.length);getShortWeekdays()得到的数组的长度是8,下标为0的是没有值1为星期日...7为星期六
//注释代码1
//Java核心技术的代码
/*
do {
//System.out.printf("%4s", weekDayNames[weekDay]); //经过上面定义索引,weekDay代表的是本星期日
d.add(Calendar.DAY_OF_MONTH, 1); //天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK); //重新获得weekDay的值
} while (weekDay != firstDayOfWeek); //当循环完一个星期后,这里判断不成立,退出循环
*/
//我写的代码,替换上面注释代码1
for (int i=1; iweekDayNames.length; i++)//打印星期标题
System.out.printf("%3s\t", weekDayNames[i]);//引号内是一个全角的空格,因为是中文版,不是书上英文环境,中文和空格对于不上,这里我们用\t解决
//System.out.printf("%3s ", weekDayNames[i]); //方式2
System.out.println();//换行
for (int i=1; i=indent; i++)//确定一星期的一天位置,利用上面indent
System.out.printf("\t");//如用方式2,则这里内容是四个全角空格
//实现输出日期
d.set(Calendar.MONTH, month);
d.set(Calendar.DAY_OF_MONTH, 1);
do {
//print day
int day = d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
if (day == today)
System.out.print("*");
System.out.print("\t");
d.add(Calendar.DATE, 1);//天数加1
weekDay = d.get(Calendar.DAY_OF_WEEK);//刷新weekDay
if (weekDay == firstDayOfWeek) //如果这天等于星期天则换行
System.out.println();
} while (d.get(Calendar.MONTH) == month);
}
}
class CalendarList{
int year,month;
int dayNum,i,num,count=0;
Calendar objCalendar;
int[] arrDayNum=;
CalendarList(){
objCalendar=Calendar.getInstance();
this.year=objCalendar.get(Calendar.YEAR);
this.month=objCalendar.get(Calendar.MONTH)+1; //要+1
}
CalendarList(String args0,String args1){
this.year=Integer.parseInt(args1);
this.month=Integer.parseInt(args0);
objCalendar=Calendar.getInstance();//这里没有get
objCalendar.set(Calendar.YEAR,year);//set是这样用的
objCalendar.set(Calendar.MONTH,month-1);
}
void display(){
System.out.println("\t\t\t"+year+"年"+month+"月");
System.out.println("日 一 二 三 四 五 六"); //每个空3个空格
num=objCalendar.get(Calendar.DAY_OF_WEEK);
if ((year/4==0year/100!=0)||(year/400==0)){
arrDayNum[1]+=1;
}
for (i=1;i=12;i++){
if (i==month){
dayNum=arrDayNum[i-1];
break;
}
}
for(i=1;i=num;i++){
System.out.print(" ");//5个空格
count++;
}
for (i=1;i=dayNum;i++){
System.out.print(i10?" "+i+" ":i+" "); //自己改了下 ,空格数:1,3,3
count++;
if(count==7){
System.out.println();
count=0;
}
}
System.out.println ();
}
}
public class MainClass {
public static void main(String[] args) {
CalendarList objCalendar=new CalendarList();
CalendarList objCalendar1=new CalendarList("11","2007");
objCalendar.display();
objCalendar1.display();
}
}