用java编写小日历

怎么用java日历

以下是两个类,请楼主分别存成两个java文件:

其中

MainFrame.java是显示日历程序,Clock.java是日历计算程序。编译后运行MainFrame这个类即可。

1.MainFrame.java

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;

public 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();

}

}

2.Clock.java

—–

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;

//显示时间的类:Clock

/** *//**

* 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);

}

}

如何用JAVA写日历?

按照你的要求编写的Java日历验证程序如下

UI.java

import java.util.Scanner;

public class UI {

 static Scanner sc=new Scanner(System.in);

 public static int askInt(String s){

  System.out.print(s);

  return sc.nextInt();

 }

 public static void println(String s){

  System.out.println(s);

 }

}

EE.java

public class EE {

 public void validateDateCore(){

  int year =UI.askInt(“Enter the year: “);

  int month=UI.askInt(“Enter the month: “);

  int day=UI.askInt(“Enter the day: “);

  if(year  1){

   UI.println(“The year is not a valid number.”);

   return;

  }

  if(month1 || month12){

   UI.println(“The month is not a valid number.”);

   return;

  }

  int monthDay=0;

  switch(month){

   case 1:

   case 3:

   case 5:

   case 7:

   case 8:

   case 10:

   case 12:monthDay=31;break;

   case 4:

   case 6:

   case 9:

   case 11:monthDay=30;break;

   case 2:

    if((year%4==0  year%100!=0) || year%400==0){

     monthDay=29;

    }else{

     monthDay=28;

    }

    break;

  }

  if(day1 || daymonthDay){

   UI.println(“The day is not a valid number.”);

   return;

  }else{

   UI.println(“It is “+day+”/”+month+”/”+year+”.”);

  }

 }

 public static void main(String[] args) {

  new EE().validateDateCore();

 }

}

运行结果

帮忙用JAVA编写一个简单的日历

这是我几年前写的

import java.util.ArrayList;

import java.util.Calendar;

import java.util.List;

public class $ {

    private static int[] DAYS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    public static void main(String[] args) {

        long l1 = System.currentTimeMillis();

        List data = rili(2015, 1, 2015, 12);

        long l2 = System.currentTimeMillis();

        for (int i = 0; i  data.size(); i++) {

            System.out.println(data.get(i));

        }

        System.out.println((l2 – l1) + “MS”);

    }

    private static List rili(int startYear, int startMonth, int endYear, int endMonth) {

        if (startYear  endYear || (startYear == endYear  startMonth  endMonth)) {

            return null;

        }

        List data = new ArrayList();

        for (int ii = startYear; ii = endYear; ii++) {

            int startM = startMonth – 1;

            int endM = endMonth – 1;

            if (startYear  endYear) {

                if (ii == endYear) {

                    endM = 11;

                } else {

                    startM = 0;

                }

            }

            for (int i = startM; i = endM; i++) {

                data.add(“———————–” + ii + “年” + (i + 1) + “月———————–“);

                data.add(“日\t一\t二\t三\t四\t五\t六”);

                int day = days(ii, i);

                StringBuffer buf = new StringBuffer();

                int idx = 1;

                while (idx = day) {

                    int len = 0;

                    if (idx == 1) {

                        Calendar c = Calendar.getInstance();

                        c.set(ii, i, idx);

                        int xingqi = c.get(Calendar.DAY_OF_WEEK);

                        len = getLen(xingqi);

                        buf.append(addBlank(len));

                    }

                    buf.append(idx++);

                    for (int k = len + 1; k  7; k++) {

                        if (idx  day) {

                            break;

                        }

                        buf.append(“\t” + (idx++));

                    }

                    buf.append(“\n”);

                }

                data.add(buf);

            }

        }

        return data;

    }

    private static StringBuffer addBlank(int len) {

        StringBuffer buf = new StringBuffer();

        for (int index = 0; index  len; index++) {

            buf.append(“\t”);

        }

        return buf;

    }

    private static int getLen(int xingqi) {

        return xingqi == Calendar.SUNDAY ? 0 : xingqi – 1;

    }

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

        if (month != 1) {

            return DAYS[month];

        }

        if ((year % 4 == 0  year % 100 != 0) || year % 400 == 0) {

            return 29;

        }

        return DAYS[month];

    }

}

怎样用java编写日历

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();

}

}

用java编写小日历

java语言编写日历

import java.util.*;

public class calendar

{

public static void main(String[] args)

{

new calendar().makeCalendar();

}

public void makeCalendar()

{

int i;

int j;

int year = 0;

int month = 0;

int week = 0;

int totalDay = 0;

Scanner scanner = new Scanner(System.in);

Calendar ca = Calendar.getInstance();

printAsterisk();

System.out.print(“欢 迎 使 用 万 年 历”);

printAsterisk();

System.out.print(“\n\n请输入年份:”);

year = scanner.nextInt();

System.out.print(“\n\n请输入月份:”);

month = scanner.nextInt() ;

ca.set(year, month – 1,1);

week = ca.get(Calendar.DAY_OF_WEEK)-1;//获取输入月第一天是星期几

if( month != 2)

totalDay = calculatetotalDay(year , month);

else

{

if(judgeLeap_year(year))

totalDay = calculatetotalDay(year , month) + 1;//如果是闰年,加一天

else

totalDay = calculatetotalDay(year , month);

}

System.out.println(“\n\n\n星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六”);

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

{

System.out.print(“\t”);

}

for( i = 1; i (8 – week);i++)

System.out.print(i + “\t”);

for( i = (8 – week),j = 0;i = totalDay;i++,j++)

{

if(j % 7 == 0)

System.out.println();

System.out.print(i+”\t”);

}

}

public void printAsterisk()

{

int i;

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

System.out.print(“*”);

}

//获取输入月的天数

public int calculatetotalDay(int year ,int month)

{

int result = 0;

switch (month)

{

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12: result = 31;

break;

case 4:

case 6:

case 9:

case 11:result = 30;

break;

default:result = 28;

break;

}

return result;

}

//判断闰年

public boolean judgeLeap_year(int year)

{

if((year % 4 == 0 year % 100 != 0) || year % 400 == 0)

return true;

else

return false;

}

}

编写JAVA程序实现一个简单的日历(高分求高手)(追加分)

import java.awt.*;

import java.awt.event.*;

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.white;

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;

public MyCalendar() {

cPane = (JPanel) getContentPane();

}

public void init() {

cPane.setLayout(new BorderLayout());

calendar = Calendar.getInstance();

calendar = Calendar.getInstance();

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 7;

}

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);

}

}

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(“Calendar Application”);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyCalendar myCalendar = new MyCalendar();

myCalendar.init();

frame.getContentPane().add(myCalendar);

frame.setSize(240, 172);

frame.show();

}

}

本文来自投稿,不代表【】观点,发布者:【

本文地址: ,如若转载,请注明出处!

举报投诉邮箱:253000106@qq.com

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2024年3月27日 05:13:22
下一篇 2024年3月27日 05:20:34

相关推荐

  • 深入java虚拟机pdf,深入java虚拟机 中村成洋 pdf

    在linux环境下,java怎么实现从word格式转换为pdf格式 //设置当前使用的打印机,我的Adobe Distiller打印机名字为 Adobe PDF wordCom.setProperty( ActivePrinter , new Variant( Adobe PDF ));//设置printout的参数,将word文档打印为postscript…

    2024年5月23日
    4400
  • java截取指定长度字符串,java截取指定字符串之后的

    java中如何截取字符串中的指定一部分 第一个参数是开始截取的字符位置。(从0开始)第二个参数是结束字符的位置+1。(从0开始)indexof函数的作用是查找该字符串中的某个字的位置,并且返回。 int end);截取s中从begin开始至end结束时的字符串,并将其赋值给s;split讲解:java.lang.string.split split 方法 将…

    2024年5月23日
    4200
  • java绑定一个端口,java使用端口

    java如何多个service共用一个端口 你如果有多个项目的话,你可以把多个项目放到一个tomcat里面,这样端口相同使用项目名称来进行区分项目。你如果非要使用同一个,你也可以配置不同的域名导向不同的项目。就是访问的域名不同转接到的项目不同。 如果需要同时启动多个程序,要么修改tomcat的配置文件中的监听端口。要么修改jar包程序的监听端口。不能在一台服…

    2024年5月23日
    3400
  • java多线程并发编程基础,Java多线程并发执行返回

    电脑培训分享Java并发编程:核心理论 电脑培训发现本系列会从线程间协调的方式(wait、notify、notifyAll)、Synchronized及Volatile的本质入手,详细解释JDK为我们提供的每种并发工具和底层实现机制。 人们开始意识到了继承的众多缺点,开始努力用聚合代替继承。软件工程解决扩展性的重要原则就是抽象描述,直接使用的工具就是接口。接…

    2024年5月23日
    4600
  • 自学java找工作,自学java找工作需要包装简历吗

    自学java学多久可以找到工作 1、自学Java至少需要一年以上的时间才能达到找工作的水平。报班培训四到六个月的时间就可以找到一份不错的工作。 2、自学Java至少需要一年以上的时间才能达到找工作的水平。 3、如果要想找到一份Java相关的工作,需要至少学习5-6个月时间才能就业。Java开发需要掌握一些基础的编程语言知识,比如掌握面向对象的编程思想、基本的…

    2024年5月23日
    4300
  • java左移右移,java 左移

    java位移问题 1、思路:直接用Integer类的bit运算操作。 2、移位操作:左移:向左移位,符号后面的数字是移了多少位,移的位用0补齐,例如2进制数01111111左移一位后变为11111110,移位是字节操作。 3、Java 位运算 Java 位运算[转]一,Java 位运算表示方法: 在Java语言中,二进制数使用补码表示,最高位为符号位,正数的…

    2024年5月23日
    4200
  • java技术规范,java规范性要求

    现在主流的JAVA技术是什么? java最流行开发技术程序员必看 1 、Git Git一直是世界上最受欢迎的Java工具之一,也是Java开发人员最杰出的工具之一。Git是一个开源工具,是-种出色的分布式版本控制解决方案。 (1).Java基础语法、数组、类与对象、继承与多态、异常、范型、集合、流与文件、反射、枚举、自动装箱和注解。(2).Java面向对象编…

    2024年5月23日
    4000
  • javasocket编程,Java socket编程中,禁用nagle算法的参数

    Java进行并发多连接socket编程 1、Java可利用ServerSocket类对外部客户端提供多个socket接口。基本的做法是先创建一个ServerSocket实例,并绑定一个指定的端口,然后在这个实例上调用accept()方法等待客户端的连接请求。 2、Socket socket=server.accept(0;Thread handleThrea…

    2024年5月23日
    4600
  • java死亡,java死代码是什么意思

    我的世界传送回死亡点指令是什么? 1、下面就让我们一起来了解一下吧:我的世界回到死的地方的指令是输入/back,就可以回到死亡地点了,当然也可以看信标,因为死亡后会有一道光集中在死亡点,只要循着光就可以找到目的地了。 2、在服务器中的指令 首先打开指令台,在指令行输入“/back”就可以回到自己的死亡地点了。在单人游戏中的指令 在单人游戏中,您无法直接返回到…

    2024年5月23日
    4800
  • myeclipse能部署java工程么,myeclipse支持jdk18

    myeclipse如何建java文件 1、点击【File】—【New】–【Class】在如下界面,输入Class的名字,如Test,点击【Finish】。Test.java文件创建成功。 2、点击【File】—【New】–【Class】 在如下界面,输入Class的名字,如Test,点击【Finish】。 Te…

    2024年5月23日
    3900

发表回复

登录后才能评论



关注微信