您的位置:

java万年历表(万年历java代码讲解)

本文目录一览:

用java控制台实现万年历-要求打印当前年月日的日历表格,要求对当天的日期单独标示

以下是用java swing编写的日历,很好用,在我所做的系统里就能够正常的使用

接下来 是具体代码:

package Demo;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.Frame;

import java.awt.GridLayout;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JFormattedTextField;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JSpinner;

import javax.swing.SpinnerNumberModel;

import javax.swing.SwingConstants;

import javax.swing.SwingUtilities;

import javax.swing.border.LineBorder;

import javax.swing.event.ChangeEvent;

import javax.swing.event.ChangeListener;

public class DateChooser extends JPanel implements ActionListener,

ChangeListener {

/**

*

*/

private static final long serialVersionUID = 1L;

int startYear = 1980;

int lastYear = 2050;

int width = 270;

int height = 200;

Color backGroundColor = Color.gray;

Color palletTableColor = Color.white;

Color todayBackColor = Color.orange;

Color weekFontColor = Color.blue;

Color dateFontColor = Color.black;

Color weekendFontColor = Color.red;

Color controlLineColor = Color.pink;

Color controlTextColor = Color.white;

Color rbFontColor = Color.white;

Color rbBorderColor = Color.red;

Color rbButtonColor = Color.pink;

Color rbBtFontColor = Color.red;

JDialog dialog;

JSpinner yearSpin;

JSpinner monthSpin;

JSpinner hourSpin;

JSpinner minuteSpin;

JButton[][] daysButton = new JButton[6][7];

JFormattedTextField jFormattedTextField;

Calendar c = getCalendar();

DateChooser(JFormattedTextField jftf) {

jFormattedTextField = jftf;

setLayout(new BorderLayout());

setBorder(new LineBorder(backGroundColor, 2));

setBackground(backGroundColor);

JPanel topYearAndMonth = createYearAndMonthPanal();

add(topYearAndMonth, BorderLayout.NORTH);

JPanel centerWeekAndDay = createWeekAndDayPanal();

add(centerWeekAndDay, BorderLayout.CENTER);

}

private JPanel createYearAndMonthPanal() {

int currentYear = c.get(Calendar.YEAR);

int currentMonth = c.get(Calendar.MONTH) + 1;

int currentHour = c.get(Calendar.HOUR_OF_DAY);

int currentMinute = c.get(Calendar.MINUTE);

JPanel result = new JPanel();

result.setLayout(new FlowLayout());

result.setBackground(controlLineColor);

yearSpin = new JSpinner(new SpinnerNumberModel(currentYear, startYear,

lastYear, 1));

yearSpin.setPreferredSize(new Dimension(48, 20));

yearSpin.setName("Year");

yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));

yearSpin.addChangeListener(this);

result.add(yearSpin);

JLabel yearLabel = new JLabel("年");

yearLabel.setForeground(controlTextColor);

result.add(yearLabel);

monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1, 12, 1));

monthSpin.setPreferredSize(new Dimension(35, 20));

monthSpin.setName("Month");

monthSpin.addChangeListener(this);

result.add(monthSpin);

JLabel monthLabel = new JLabel("月");

monthLabel.setForeground(controlTextColor);

result.add(monthLabel);

hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23, 1));

hourSpin.setPreferredSize(new Dimension(35, 20));

hourSpin.setName("Hour");

hourSpin.addChangeListener(this);

result.add(hourSpin);

JLabel hourLabel = new JLabel("时");

hourLabel.setForeground(controlTextColor);

result.add(hourLabel);

minuteSpin = new JSpinner(new SpinnerNumberModel(currentMinute, 0, 59,

1));

minuteSpin.setPreferredSize(new Dimension(35, 20));

minuteSpin.setName("Minute");

minuteSpin.addChangeListener(this);

result.add(minuteSpin);

JLabel minuteLabel = new JLabel("分");

minuteLabel.setForeground(controlTextColor);

result.add(minuteLabel);

return result;

}

private JPanel createWeekAndDayPanal() {

String colname[] = { "日", "一", "二", "三", "四", "五", "六" };

JPanel result = new JPanel();

result.setFont(new Font("宋体", Font.PLAIN, 12));

result.setLayout(new GridLayout(7, 7));

result.setBackground(Color.white);

JLabel cell;

for (int i = 0; i 7; i++) {

cell = new JLabel(colname[i]);

cell.setHorizontalAlignment(JLabel.CENTER);

if (i == 0 || i == 6)

cell.setForeground(weekendFontColor);

else

cell.setForeground(weekFontColor);

result.add(cell);

}

int actionCommandId = 0;

for (int i = 0; i 6; i++)

for (int j = 0; j 7; j++) {

JButton numberButton = new JButton();

numberButton.setBorder(null);

numberButton.setHorizontalAlignment(SwingConstants.CENTER);

numberButton.setActionCommand(String.valueOf(actionCommandId));

numberButton.addActionListener(this);

numberButton.setBackground(palletTableColor);

numberButton.setForeground(dateFontColor);

if (j == 0 || j == 6)

numberButton.setForeground(weekendFontColor);

else

numberButton.setForeground(dateFontColor);

daysButton[i][j] = numberButton;

numberButton.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

if (e.getClickCount() == 2) {

closeAndSetDate();

}

}

});

result.add(numberButton);

actionCommandId++;

}

return result;

}

private JDialog createDialog(Frame owner) {

JDialog result = new JDialog(owner, "日期时间选择", true);

result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);

result.getContentPane().add(this, BorderLayout.CENTER);

result.pack();

result.setSize(width, height);

return result;

}

public void showDateChooser(Point position) {

Object tmpobj=SwingUtilities.getWindowAncestor(jFormattedTextField);

if(tmpobj.getClass().isInstance(new JDialog())||tmpobj.getClass().getSuperclass().isInstance(new JDialog()))

{

JDialog ownerdialog = (JDialog) SwingUtilities

.getWindowAncestor(jFormattedTextField);

Frame owner = (Frame) SwingUtilities.getWindowAncestor(ownerdialog);

if (dialog == null || dialog.getOwner() != owner) {

dialog = createDialog(owner);

}

dialog.setLocation(getAppropriateLocation(owner, position));

}

else if(tmpobj.getClass().isInstance(new JFrame())||tmpobj.getClass().getSuperclass().isInstance(new JFrame()))

{

JFrame ownerFrame = (JFrame) SwingUtilities

.getWindowAncestor(jFormattedTextField);

if (dialog == null || dialog.getOwner() != ownerFrame) {

dialog = createDialog(ownerFrame);

}

dialog.setLocation(getAppropriateLocation(ownerFrame, position));

}

flushWeekAndDay();

dialog.setVisible(true);

}

Point getAppropriateLocation(Frame owner, Point position) {

Point result = new Point(position);

Point p = owner.getLocation();

int offsetX = (position.x + width) - (p.x + owner.getWidth());

int offsetY = (position.y + height) - (p.y + owner.getHeight());

if (offsetX 0) {

result.x -= offsetX;

}

if (offsetY 0) {

result.y -= offsetY;

}

return result;

}

public void closeAndSetDate() {

setDate(c.getTime());

dialog.dispose();

}

private Calendar getCalendar() {

Calendar result = Calendar.getInstance();

result.setTime(getDate());

return result;

}

private int getSelectedYear() {

return ((Integer) yearSpin.getValue()).intValue();

}

private int getSelectedMonth() {

return ((Integer) monthSpin.getValue()).intValue();

}

private int getSelectedHour() {

return ((Integer) hourSpin.getValue()).intValue();

}

private int getSelectedMinute() {

return ((Integer) minuteSpin.getValue()).intValue();

}

private void dayColorUpdate(boolean isOldDay) {

int day = c.get(Calendar.DAY_OF_MONTH);

c.set(Calendar.DAY_OF_MONTH, 1);

int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);

int i = actionCommandId / 7;

int j = actionCommandId % 7;

if (isOldDay)

daysButton[i][j].setForeground(dateFontColor);

else

daysButton[i][j].setForeground(todayBackColor);

}

private void flushWeekAndDay() {

c.set(Calendar.DAY_OF_MONTH, 1);

int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);

int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);

for (int i = 0; i 6; i++) {

for (int j = 0; j 7; j++) {

String s = "";

if (dayNo = 1 dayNo = maxDayNo)

s = String.valueOf(dayNo);

daysButton[i][j].setText(s);

dayNo++;

}

}

dayColorUpdate(false);

}

public void stateChanged(ChangeEvent e) {

JSpinner source = (JSpinner) e.getSource();

if (source.getName().equals("Minute")) {

c.set(Calendar.MINUTE, getSelectedMinute());

return;

}

if (source.getName().equals("Hour")) {

c.set(Calendar.HOUR_OF_DAY, getSelectedHour());

return;

}

dayColorUpdate(true);

if (source.getName().equals("Year")) {

c.set(Calendar.YEAR, getSelectedYear());

}

if (source.getName().equals("Month")) {

c.set(Calendar.MONTH, getSelectedMonth() - 1);

}

flushWeekAndDay();

}

public void actionPerformed(ActionEvent e) {

JButton source = (JButton) e.getSource();

if (source.getText().length() == 0)

return;

dayColorUpdate(true);

source.setForeground(todayBackColor);

int newDay = Integer.parseInt(source.getText());

c.set(Calendar.DAY_OF_MONTH, newDay);

}

public void setDate(Date date) {

jFormattedTextField.setText(getDefaultDateFormat().format(date));

}

public Date getDate() {

try {

String dateString = jFormattedTextField.getText();

return getDefaultDateFormat().parse(dateString);

} catch (ParseException e) {

return getNowDate();

} catch (Exception ee) {

return getNowDate();

}

}

private static Date getNowDate() {

return Calendar.getInstance().getTime();

}

private static SimpleDateFormat getDefaultDateFormat() {

return new SimpleDateFormat("yyyy-MM-dd HH:mm");

}

}

测试程序:

package Demo;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFormattedTextField;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

public class DemoForDateChooser extends JFrame {

private JFormattedTextField formattedTextField;

/**

* Launch the application

* @param args

*/

public static void main(String args[]) {

try {

DemoForDateChooser frame = new DemoForDateChooser();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* Create the frame

*/

public DemoForDateChooser() {

super();

setTitle("日期选择框");

getContentPane().setLayout(null);

setBounds(100, 100, 383, 137);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JPanel panel = new JPanel();

panel.setLayout(null);

panel.setBounds(0, 0, 375, 107);

getContentPane().add(panel);

formattedTextField = new JFormattedTextField();

formattedTextField.setBounds(68, 48, 175, 23);

final JButton button = new JButton();

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

DateChooser mDateChooser=new DateChooser(formattedTextField);

Point p = button.getLocationOnScreen();

p.y = p.y + 30;

mDateChooser.showDateChooser(p);

formattedTextField.requestFocusInWindow();

}

});

button.setText("选择日期");

button.setBounds(249, 47, 99, 23);

panel.add(button);

final JLabel label = new JLabel();

label.setText("日期:");

label.setBounds(10, 47, 71, 23);

panel.add(label);

panel.add(formattedTextField);

//

}

}

用Java编写一个万年历

package com.baidu;

/**

* MainFrame.java

* Summary 万年历主类

* Created on

* @author

* remark 如有改动请发一份代码给我,邮箱wsh.grxx@163.com

*/

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.GridLayout;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.Date;

import java.util.Calendar;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

class MainFrame extends JFrame {

/** */

/**

*

*/

private static final long serialVersionUID = 1L;

JPanel panel = new JPanel(new BorderLayout());

JPanel panel1 = new JPanel();

JPanel panel2 = new JPanel(new GridLayout(7, 7));

JPanel panel3 = new JPanel();

JLabel[] label = new JLabel[49];

JLabel y_label = new JLabel("年份");

JLabel m_label = new JLabel("月份");

JComboBox com1 = new JComboBox();

JComboBox com2 = new JComboBox();

int re_year, re_month;

int x_size, y_size;

String year_num;

Calendar now = Calendar.getInstance(); // 实例化Calendar

MainFrame() {

super("万年历");

setSize(300, 350);

x_size = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth());

y_size = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight());

setLocation((x_size - 300) / 2, (y_size - 350) / 2);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel1.add(y_label);

panel1.add(com1);

panel1.add(m_label);

panel1.add(com2);

for (int i = 0; i 49; i++) {

label[i] = new JLabel("", JLabel.CENTER);// 将显示的字符设置为居中

panel2.add(label[i]);

}

panel3.add(new Clock(this));

panel.add(panel1, BorderLayout.NORTH);

panel.add(panel2, BorderLayout.CENTER);

panel.add(panel3, BorderLayout.SOUTH);

panel.setBackground(Color.white);

panel1.setBackground(Color.white);

panel2.setBackground(Color.white);

panel3.setBackground(Color.white);

Init();

com1.addActionListener(new ClockAction());

com2.addActionListener(new ClockAction());

setContentPane(panel);

setVisible(true);

setResizable(false);

}

class ClockAction implements ActionListener {

public void actionPerformed(ActionEvent arg0) {

int c_year, c_month, c_week;

c_year = Integer.parseInt(com1.getSelectedItem().toString()); // 得到当前所选年份

c_month = Integer.parseInt(com2.getSelectedItem().toString()) - 1; // 得到当前月份,并减1,计算机中的月为0-11

c_week = use(c_year, c_month); // 调用函数use,得到星期几

Resetday(c_week, c_year, c_month); // 调用函数Resetday

}

}

public void Init() {

int year, month_num, first_day_num;

String log[] = { "日", "一", "二", "三", "四", "五", "六" };

for (int i = 0; i 7; i++) {

label[i].setText(log[i]);

}

for (int i = 0; i 49; i = i + 7) {

label[i].setForeground(Color.red); // 将星期日的日期设置为红色

}

for (int i = 6; i 49; i = i + 7) {

label[i].setForeground(Color.green);// 将星期六的日期设置为绿色

}

for (int i = 1; i 10000; i++) {

com1.addItem("" + i);

}

for (int i = 1; i 13; i++) {

com2.addItem("" + i);

}

month_num = (int) (now.get(Calendar.MONTH)); // 得到当前时间的月份

year = (int) (now.get(Calendar.YEAR)); // 得到当前时间的年份

com1.setSelectedIndex(year - 1); // 设置下拉列表显示为当前年

com2.setSelectedIndex(month_num); // 设置下拉列表显示为当前月

first_day_num = use(year, month_num);

Resetday(first_day_num, year, month_num);

}

public int use(int reyear, int remonth) {

int week_num;

now.set(reyear, remonth, 1); // 设置时间为所要查询的年月的第一天

week_num = (int) (now.get(Calendar.DAY_OF_WEEK));// 得到第一天的星期

return week_num;

}

@SuppressWarnings("deprecation")

public void Resetday(int week_log, int year_log, int month_log) {

int month_day_score; // 存储月份的天数

int count;

month_day_score = 0;

count = 1;

Date date = new Date(year_log, month_log + 1, 1); // now

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(Calendar.MONTH, -1); // 前个月

month_day_score = cal.getActualMaximum(Calendar.DAY_OF_MONTH);// 最后一天

for (int i = 7; i 49; i++) { // 初始化标签

label[i].setText("");

}

week_log = week_log + 6; // 将星期数加6,使显示正确

month_day_score = month_day_score + week_log;

for (int i = week_log; i month_day_score; i++, count++) {

label[i].setText(count + "");

}

}

public static void main(String[] args) {

JFrame.setDefaultLookAndFeelDecorated(true);

new MainFrame();

}

}

package com.baidu;

/**

* Clock.java

* Summary 数字时间显示

* Created on

* @author

* remark

*/

import java.awt.Canvas;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.text.SimpleDateFormat;

import java.util.Calendar;

class Clock extends Canvas implements Runnable {

/** */

/**

*

*/

private static final long serialVersionUID = 3660124045489727166L;

MainFrame mf;

Thread t;

String time;

public Clock(MainFrame mf) {

this.mf = mf;

setSize(280, 40);

setBackground(Color.white);

t = new Thread(this); // 实例化线程

t.start(); // 调用线程

}

public void run() {

while (true) {

try {

Thread.sleep(1000); // 休眠1秒钟

} catch (InterruptedException e) {

System.out.println("异常");

}

this.repaint(100);

}

}

public void paint(Graphics g) {

Font f = new Font("宋体", Font.BOLD, 16);

SimpleDateFormat SDF = new SimpleDateFormat("yyyy'年'MM'月'dd'日'HH:mm:ss");// 格式化时间显示类型

Calendar now = Calendar.getInstance();

time = SDF.format(now.getTime()); // 得到当前日期和时间

g.setFont(f);

g.setColor(Color.orange);

g.drawString(time, 45, 25);

}

}

借花献一次.记得我以前回答过一次这个问题,还好代码还在.copy一个高手的

如何用Java编写一个万年历

/*

题目:输出任意年份任意月份的日历表(公元后)

思路:

    1.已知1年1月1日是星期日,1 % 7 = 1 对应的是星期日,2 % 7 = 2 对应的是星期一,以此类推;

    2.计算当年以前所有天数+当年当月1号之前所有天数;

      a.年份分平年闰年,平年365天,闰年366天;

      b.闰年的判断方法year % 400 == 0 || (year % 100 != 0  year % 4 == 0)若为真,则为闰年否则为平年;

      c.定义平年/闰年数组,包含各月天数;

      d.遍历数组求和,计算当年当月前总天数;

      e.当年以前所有天数+当年当月前总天数+1即为1年1月1日到当年当月1日的总天数;

    3.总天数对7取模,根据结果判断当月1号是星期几,输出空白区域;

    4.输出当月日历表,逢星期六换行

*/

import java.util.Scanner;

class FindMonthList {

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        System.out.println("请输入年份:");

        int year = sc.nextInt();            //年份

        if (year  1) {                        //判断非法输入年份

            System.out.println("输入错误!");

            return;

        }

        System.out.println("请输入月份:");

        int month = sc.nextInt();            //月份

        if (month  1 || month  12) {        //判断非法输入月份

            System.out.println("输入错误!");

            return;

        }

        //输出表头

        System.out.println("-------" + year + " 年 " + month + " 月 " + "-------");

        System.out.println();

        System.out.println("日  一  二  三  四  五  六");

        //计算当前年份以前所有天数beforeYearTotalDay;每4年一个闰年,闰年366天,平年365天

        int beforeYearTotalDay = ((year - 1) / 4 * 366) + (year-1 - ((year - 1) / 4)) * 365;

        int[] arrLeapYear = {0,31,29,31,30,31,30,31,31,30,31,30,31};    //闰年各月天数    int数组

        int[] arrNormalYear = {0,31,28,31,30,31,30,31,31,30,31,30,31};    //平年各月天数    int数组

        int beforeMonthTotalDay = 0;                                    //定义本年当月之前月份的总天数

        if (year % 400 == 0 || (year % 100 != 0  year % 4 == 0)) {    //判断当前年份是否是闰年

            for (int i = 0 ; i  month ; i ++ ) {    //for循环计算当月之前总天数

                //计算当前月份之前的所有天数

                beforeMonthTotalDay = beforeMonthTotalDay + arrLeapYear[i];

            }

            //判断当月1日是星期几

            int totalDay = beforeYearTotalDay + beforeMonthTotalDay + 1;

            int week = totalDay % 7;//已知1年1月1日是星期日,即模7得1对应的是星期日

            for (int i = 0 ; i  (week - 1 + 7) % 7 ; i ++) {    //如果写成i  (week-1)会出现i-1的情况

                System.out.print("    ");//输出开头空白

            }

            for (int i = 1 ;i = arrLeapYear[month] ;i ++ ) {    //for循环输出各月天数

                System.out.print(i + "  ");

                if (i  10 ) {        //小于10的数补一个空格,以便打印整齐

                    System.out.print(" ");

                }

                if (i % 7 == ((7-(week - 1)) % 7 ) || i == arrLeapYear[month]) {//每逢星期六/尾数换行

                    System.out.println();

                }

            }

        } else {        //不是闰年就是平年

            for (int i = 0 ; i  month ; i ++ ) {    //for循环计算出当月之前月份总天数

                beforeMonthTotalDay = beforeMonthTotalDay + arrNormalYear[i];

            }

            //判断当月1日是星期几

            int totalDay = beforeYearTotalDay + beforeMonthTotalDay + 1;

            int week = totalDay % 7;//已知1年1月1日是星期日,即模7得1对应的是星期日

            for (int i = 0 ; i  (week - 1 + 7) % 7 ; i ++) {    //如果写成i  (week-1)会出现i-1的情况

                System.out.print("    ");//输出开头空白

            }

            for (int i = 1 ;i = arrNormalYear[month] ;i ++ ) {//for循环输出各月天数

                System.out.print(i + "  ");

                if (i  10 ) {            //小于10的数补一个空格,以便打印整齐

                    System.out.print(" ");

                }

                if (i % 7 == ((7-(week - 1)) % 7 ) || i == arrNormalYear[month]) {//每逢星期六/尾数换行

                    System.out.println();

                }

            }

        }

    }

}

怎么用JAVA编写万年历!

/*

题目:输出任意年份任意月份的日历表(公元后)

思路:

    1.已知1年1月1日是星期日,1 % 7 = 1 对应的是星期日,2 % 7 = 2 对应的是星期一,以此类推;

    2.计算当年以前所有天数+当年当月1号之前所有天数;

      a.年份分平年闰年,平年365天,闰年366天;

      b.闰年的判断方法year % 400 == 0 || (year % 100 != 0  year % 4 == 0)若为真,则为闰年否则为平年;

      c.定义平年/闰年数组,包含各月天数;

      d.遍历数组求和,计算当年当月前总天数;

      e.当年以前所有天数+当年当月前总天数+1即为1年1月1日到当年当月1日的总天数;

    3.总天数对7取模,根据结果判断当月1号是星期几,输出空白区域;

    4.输出当月日历表,逢星期六换行

*/

import java.util.Scanner;

class FindMonthList {

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        System.out.println("请输入年份:");

        int year = sc.nextInt();            //年份

        if (year  1) {                        //判断非法输入年份

            System.out.println("输入错误!");

            return;

        }

        System.out.println("请输入月份:");

        int month = sc.nextInt();            //月份

        if (month  1 || month  12) {        //判断非法输入月份

            System.out.println("输入错误!");

            return;

        }

        //输出表头

        System.out.println("-------" + year + " 年 " + month + " 月 " + "-------");

        System.out.println();

        System.out.println("日  一  二  三  四  五  六");

        //计算当前年份以前所有天数beforeYearTotalDay;每4年一个闰年,闰年366天,平年365天

        int beforeYearTotalDay = ((year - 1) / 4 * 366) + (year-1 - ((year - 1) / 4)) * 365;

        int[] arrLeapYear = {0,31,29,31,30,31,30,31,31,30,31,30,31};    //闰年各月天数    int数组

        int[] arrNormalYear = {0,31,28,31,30,31,30,31,31,30,31,30,31};    //平年各月天数    int数组

        int beforeMonthTotalDay = 0;                                    //定义本年当月之前月份的总天数

        if (year % 400 == 0 || (year % 100 != 0  year % 4 == 0)) {    //判断当前年份是否是闰年

            for (int i = 0 ; i  month ; i ++ ) {    //for循环计算当月之前总天数

                //计算当前月份之前的所有天数

                beforeMonthTotalDay = beforeMonthTotalDay + arrLeapYear[i];

            }

            //判断当月1日是星期几

            int totalDay = beforeYearTotalDay + beforeMonthTotalDay + 1;

            int week = totalDay % 7;//已知1年1月1日是星期日,即模7得1对应的是星期日

            for (int i = 0 ; i  (week - 1 + 7) % 7 ; i ++) {    //如果写成i  (week-1)会出现i-1的情况

                System.out.print("    ");//输出开头空白

            }

            for (int i = 1 ;i = arrLeapYear[month] ;i ++ ) {    //for循环输出各月天数

                System.out.print(i + "  ");

                if (i  10 ) {        //小于10的数补一个空格,以便打印整齐

                    System.out.print(" ");

                }

                if (i % 7 == ((7-(week - 1)) % 7 ) || i == arrLeapYear[month]) {//每逢星期六/尾数换行

                    System.out.println();

                }

            }

        } else {        //不是闰年就是平年

            for (int i = 0 ; i  month ; i ++ ) {    //for循环计算出当月之前月份总天数

                beforeMonthTotalDay = beforeMonthTotalDay + arrNormalYear[i];

            }

            //判断当月1日是星期几

            int totalDay = beforeYearTotalDay + beforeMonthTotalDay + 1;

            int week = totalDay % 7;//已知1年1月1日是星期日,即模7得1对应的是星期日

            for (int i = 0 ; i  (week - 1 + 7) % 7 ; i ++) {    //如果写成i  (week-1)会出现i-1的情况

                System.out.print("    ");//输出开头空白

            }

            for (int i = 1 ;i = arrNormalYear[month] ;i ++ ) {//for循环输出各月天数

                System.out.print(i + "  ");

                if (i  10 ) {            //小于10的数补一个空格,以便打印整齐

                    System.out.print(" ");

                }

                if (i % 7 == ((7-(week - 1)) % 7 ) || i == arrNormalYear[month]) {//每逢星期六/尾数换行

                    System.out.println();

                }

            }

        }

    }

}

效果:

Java日历查询程序(万年历)

花了半个小时写了一个望采纳给好评。

import java.util.Scanner;

public class PrintCalendar {

/** Main method */

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Prompt the user to enter year

System.out.print("Enter full year (e.g., 2001): ");

int year = input.nextInt();

// Prompt the user to enter month

System.out.print("Enter month in number between 1 and 12: ");

int month = input.nextInt();

// Print calendar for the month of the year

printMonth(year, month);

}

/** Print the calendar for a month in a year */

public static void printMonth(int year, int month) {

// Print the headings of the calendar

printMonthTitle(year, month);

// Print the body of the calendar

printMonthBody(year, month);

}

/** Print the month title, e.g., May, 1999 */

public static void printMonthTitle(int year, int month) {

System.out.println(" " + getMonthName(month)

+ " " + year);

System.out.println("-----------------------------");

System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

}

/** Get the English name for the month */

public static String getMonthName(int month) {

String monthName = "";

switch (month) {

case 1: monthName = "January"; break;

case 2: monthName = "February"; break;

case 3: monthName = "March"; break;

case 4: monthName = "April"; break;

case 5: monthName = "May"; break;

case 6: monthName = "June"; break;

case 7: monthName = "July"; break;

case 8: monthName = "August"; break;

case 9: monthName = "September"; break;

case 10: monthName = "October"; break;

case 11: monthName = "November"; break;

case 12: monthName = "December";

}

return monthName;

}

/** Print month body */

public static void printMonthBody(int year, int month) {

// Get start day of the week for the first date in the month

int startDay = getStartDay(year, month);

// Get number of days in the month

int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

// Pad space before the first day of the month

int i = 0;

for (i = 0; i startDay; i++)

System.out.print(" ");

for (i = 1; i = numberOfDaysInMonth; i++) {

System.out.printf("%4d", i);

if ((i + startDay) % 7 == 0)

System.out.println();

}

System.out.println();

}

/** Get the start day of month/1/year */

public static int getStartDay(int year, int month) {

final int START_DAY_FOR_JAN_1_1800 = 3;

// Get total number of days from 1/1/1800 to month/1/year

int totalNumberOfDays = getTotalNumberOfDays(year, month);

// Return the start day for month/1/year

return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;

}

/** Get the total number of days since January 1, 1800 */

public static int getTotalNumberOfDays(int year, int month) {

int total = 0;

// Get the total days from 1800 to 1/1/year

for (int i = 1800; i year; i++)

if (isLeapYear(i))

total = total + 366;

else

total = total + 365;

// Add days from Jan to the month prior to the calendar month

for (int i = 1; i month; i++)

total = total + getNumberOfDaysInMonth(year, i);

return total;

}

/** Get the number of days in a month */

public static int getNumberOfDaysInMonth(int year, int month) {

if (month == 1 || month == 3 || month == 5 || month == 7 ||

month == 8 || month == 10 || month == 12)

return 31;

if (month == 4 || month == 6 || month == 9 || month == 11)

return 30;

if (month == 2) return isLeapYear(year) ? 29 : 28;

return 0; // If month is incorrect

}

/** Determine if it is a leap year */

public static boolean isLeapYear(int year) {

return year % 400 == 0 || (year % 4 == 0 year % 100 != 0);

}

}

在java里怎么做万年历,一年的啊

先上张效果图:以下是实现代码:/*日历*/

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import java.util.regex.Pattern;

import javax.swing.*;

public class Demo28 extends JFrame {

int m = 1;

String[] monthchoose = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",

"11", "12" }; // 存放月份的字符数组

String[] columnNames = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; // 存放星期的字符数组

Calendar ca = Calendar.getInstance();

Container contentPane = getContentPane();

VectorString vector = new VectorString();

String[][] date = new String[6][7]; // 表格的显示数据的格式

TextField tf; // 文本框的值代表的是年份

JComboBox jb;

JTable table; // 把日期用table的方式显示出来

public void getDate(String year, String month, String week, int Max_Day) {

int n = 0, b = 0;

// 动态把传进来月份的天数存放到容器里

for (int j = 1; j = Max_Day; j++) {

vector.add(String.valueOf(j));

}

//每次往table里添加数据的时候,都预先把原table里 的 数据清空

for(int x = 0;xdate.length;x++){

for(int y = 0;ydate[x].length;y++){

date[x][y] = null;

}

}

// 根据传进来月份的第一天是星期几,来构建Table

for (int a = Integer.parseInt(week) - 1; a date[0].length; a++) {

date[0][a] = new String((String) vector.toArray()[n]);

n++;

}

for (int i = 1; i date.length; i++) {

for (int j = 0; j date[i].length; j++) {

if (n vector.size()) {

date[i][j] = new String((String) vector.toArray()[n]);

n++;

} else

break;

}

}

// 把容器里的数据全部清除,以备下次再存放新的数据

while (b vector.size()) {

vector.remove(b);

}

}

public void chooseDate(String day) {

JLabel label = new JLabel();

for (int y = 0; y date.length; y++) {

for (int z = 0; z date[y].length; z++) {

System.out.print(date[y][z] + " ");

System.out.println(day);

if (date[y][z] != null) {

if (date[y][z].equals(day)) {

table.setSelectionBackground(Color.yellow);

return;

}

}

}

}

}

public void paint() {

setTitle("日历");

setBounds(200, 200, 350, 178);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

int m = 0;

String year = String.valueOf(ca.get(Calendar.YEAR)); // 得到当前的系统时间的年份,并把这个数值存放到year这个变量里

String month = String.valueOf(ca.get(Calendar.MONTH) + 1); // 得到当前的系统时间的月份,并把这个数值存放到month这个变量里

String day = String.valueOf(ca.get(Calendar.DATE)); // 得到当前的系统时间的日期,并把这个数值存放到day这个变量里

ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1

String week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几

int Max_Day = ca.getActualMaximum(Calendar.DATE); // 得到当前系统时间月份有多少天

getDate(year, month, week, Max_Day);

// 从月份数组里取出与当前系统时间一样的月份值

for (int i = 0; i monthchoose.length; i++) {

if (monthchoose[i].equals(month)) {

m = i;

}

}

JToolBar toolBar = new JToolBar();

JButton b1 = new JButton("<");

b1.addMouseListener(new myMouseListener1());

JButton b2 = new JButton(">");

b2.addMouseListener(new myMouseListener2());

JLabel j1 = new JLabel("年");

JLabel j2 = new JLabel("月");

tf = new TextField(5);

tf.addKeyListener(new myKeyListener());

tf.setText(year);

jb = new JComboBox(monthchoose);

jb.setSelectedIndex(m);

jb.addActionListener(new myActionListener3());

table = new JTable(date, columnNames);

//table.addMouseListener(new tableMouseListener());

table.setPreferredScrollableViewportSize(new Dimension(350, 150));

JScrollPane jsp = new JScrollPane(table);

contentPane.add(jsp, BorderLayout.CENTER);

chooseDate(day);

toolBar.add(b1);

toolBar.add(tf);

toolBar.add(b2);

toolBar.add(j1);

toolBar.add(jb);

toolBar.add(j2);

toolBar.setLocation(0, 0);

toolBar.setSize(400, 15);

contentPane.add(toolBar, BorderLayout.NORTH);

setVisible(true);

new Thread(new PaintThread()).start(); // 调用内部类PaintThread,根据里面的设置来重画

}

public static void main(String[] args) {

Demo28 d28 = new Demo28();

d28.paint();

}

// 鼠标单击左边按钮触发的事件

class myMouseListener1 extends MouseAdapter {

public void mouseClicked(MouseEvent e) {

String str = tf.getText().trim(); // 得到文本框的值

int i = Integer.parseInt(str);

i = i - 1;

tf.setText(String.valueOf(i));

String new_year = String.valueOf(i); // 把表示年份的文本框的值存放到变量new_year里

ca.set(Calendar.YEAR, i); // 把Calendar 对象的YEAR设置为用户设置的年份

String new_month = (String) jb.getSelectedItem(); // 得到月份值

ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的MONTH设置为用户设置的月份

ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1

String new_week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几

int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天

getDate(new_year, new_month, new_week, Max_Day);

}

}

class myKeyListener extends KeyAdapter {

public void keyReleased(KeyEvent e) {

try {

int i = Integer.parseInt(tf.getText().trim());

int key = e.getKeyCode();

if (key == KeyEvent.VK_ENTER) {

String new_year = String.valueOf(i);

ca.set(Calendar.YEAR, i); // 把Calendar对象的YEAR设置为用户设置的年份

String new_month = (String) jb.getSelectedItem(); // 得到月份值

ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的MONTH设置为用户设置的月份

ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1

String new_week = String.valueOf(ca

.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几

int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天

getDate(new_year, new_month, new_week, Max_Day);

}

} catch (NumberFormatException excption) {

System.out.println("你输入的年份不正确!");

}

}

}

// 鼠标单击右边按钮触发的事件

class myMouseListener2 extends MouseAdapter {

public void mouseClicked(MouseEvent e) {

String str = tf.getText().trim();

int i = Integer.parseInt(str);

i = i + 1;

tf.setText(String.valueOf(i));

String new_year = String.valueOf(i); // 把表示年份的文本框的值存放到变量new_year里

ca.set(Calendar.YEAR, i); // 把Calendar 对象的YEAR设置为用户设置的年份

String new_month = (String) jb.getSelectedItem(); // 得到月份值

ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的MONTH设置为用户设置的月份

ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1

String new_week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几

int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天

getDate(new_year, new_month, new_week, Max_Day);

}

}

// 鼠标单击选择框触发的事件

class myActionListener3 implements ActionListener {

public void actionPerformed(ActionEvent e) {

String new_year = String.valueOf(ca.get(Calendar.YEAR)); // 把表示年份的文本框的值存放到变量new_year里

String new_month = (String) jb.getSelectedItem(); // 得到用户设置的月份

ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的月份值设置为用户定义的月份

ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1

String new_week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几

int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天

getDate(new_year, new_month, new_week, Max_Day);

}

}

// 重画组件

private class PaintThread implements Runnable {

public void run() {

while (true) {

repaint();

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}