java日曆腳本,java課程設計日曆記事本代碼

本文目錄一覽:

如何用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製作日曆

package com;import java.awt.Color;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.util.Date;import java.util.GregorianCalendar;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;public class Calender2 extends JFrame implements ActionListener, ItemListener { private static final long serialVersionUID = 1L; public static void main(String args[]) { try { Calender2 frame = new Calender2(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } private Date date = new Date(); private GregorianCalendar gregorianCalendar = new GregorianCalendar(); private String[] stringWeek = new String[] { “SUN”, “MON”, “TUE”, “WED”, “THU”, “FRI”, “SAT” }; private String[] stringWeekCn = new String[] { “星期天”, “星期一”, “星期二”, “星期三”, “星期四”, “星期五”, “星期六” }; private String[] stringMonth = new String[] { “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sept”, “Oct”, “Nov”, “Dec” }; private String[] strSysTime = new String[6]; // 存儲當前日期信息 private String[] strSysNowTime = new String[6]; // 存儲運行時日期信息 private JButton[] buttonDay = new JButton[42]; private JButton[] buttonWeek = new JButton[7]; private JLabel labelMonth = new JLabel(); private JButton buttonToday = new JButton(); private JButton buttonLastMonth = new JButton(); private JButton buttonNextMonth = new JButton(); private JComboBox comboYear = new JComboBox(); private JComboBox comboMonth = new JComboBox(); public Calender2() { super(“萬年曆”); getContentPane().setLayout(new GridLayout(8, 7, 3, 5)); setBounds(250, 200, 530, 360); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); comboYear.setForeground(new Color(0, 0, 255)); comboYear.setFont(new Font(“”, Font.PLAIN, 14)); for (int y = 1900; y 2101; y++) { comboYear.addItem(” ” + new Integer(y).toString()); } getContentPane().add(comboYear); comboYear.addItemListener(this); final JLabel labelYear = new JLabel(); labelYear.setForeground(Color.BLUE); labelYear.setFont(new Font(“新宋體”, Font.PLAIN, 14)); getContentPane().add(labelYear); labelYear.setText(” 年”); comboMonth.setForeground(new Color(0, 0, 255)); comboMonth.setFont(new Font(“”, Font.PLAIN, 14)); for (int m = 1; m 13; m++) { comboMonth.addItem(” ” + new Integer(m).toString()); } getContentPane().add(comboMonth); comboMonth.addItemListener(this); getContentPane().add(labelMonth); labelMonth.setForeground(Color.BLUE); labelMonth.setFont(new Font(“新宋體”, Font.PLAIN, 14)); labelMonth.setText(” 月”); getContentPane().add(buttonLastMonth); buttonLastMonth.setForeground(Color.BLUE); buttonLastMonth.setFont(new Font(“新宋體”, Font.PLAIN, 14)); buttonLastMonth.setText(“上月”); buttonLastMonth.addActionListener(this); getContentPane().add(buttonToday); buttonToday.setForeground(Color.BLUE); buttonToday.setFont(new Font(“新宋體”, Font.PLAIN, 14)); buttonToday.setText(“今天”); buttonToday.addActionListener(this); getContentPane().add(buttonNextMonth); buttonNextMonth.setForeground(Color.BLUE); buttonNextMonth.setFont(new Font(“新宋體”, Font.PLAIN, 14)); buttonNextMonth.setText(“下月”); buttonNextMonth.addActionListener(this); for (int i = 0; i 7; i++) { buttonWeek[i] = new JButton(); if (i == 0 || i == 6) { buttonWeek[i].setForeground(Color.RED); } else { buttonWeek[i].setForeground(Color.BLUE); } buttonWeek[i].setFont(new Font(“新宋體”, Font.PLAIN, 12)); buttonWeek[i].setText(stringWeekCn[i]); getContentPane().add(buttonWeek[i]); } for (int i = 0; i 42; i++) { buttonDay[i] = new JButton(); buttonDay[i].setText(“”); getContentPane().add(buttonDay[i]); } this.setResizable(false); getSysNowTimeInfo(); setNowDate(); setNowDate(); } public void setSysDate(int year, int month) { // 將日期設置為year年month月1日 gregorianCalendar.set(year, month, 1); } public void actionPerformed(ActionEvent ae) { if (ae.getSource() == buttonToday) { setNowDate(); setNowDate(); } else if (ae.getSource() == buttonLastMonth) { setDate(-1); } else { setDate(1); } } public void itemStateChanged(ItemEvent arg0) { setDate(0); } public void getSysNowTimeInfo() { // 得到程序運行時的時間信息並存儲在字符串數組strSysNowTime中 date = gregorianCalendar.getTime(); strSysNowTime = (date + “”).split(” “); } public void getSysTimeInfo() { // 得到系統當前的時間信息並存儲在字符串數組strSysTime中 date = gregorianCalendar.getTime(); strSysTime = (date + “”).split(” “); } public int getNowMonth() { int month = 0; for (int i = 0; i 12; i++) { if (strSysNowTime[1].equalsIgnoreCase(stringMonth[i])) { month = i; break; } } return month; } public int weekStrat(String strWeek) { // 返回字符串strWeek與星期中的第幾天匹配,SUN為第一天 int strat = 0; for (int i = 0; i 7; i++) { if (strWeek.equalsIgnoreCase(stringWeek[i])) { strat = i; break; } } return strat; } public void setNowDate() { // 將時間設置為程序運行時的時間 setSysTime(getNowYear(), getNowMonth()); getSysTimeInfo(); setDayNull(); getDay(getMonthDays(getNowYear(), getNowMonth() – 1), getMonthDays( getNowYear(), getNowMonth()), weekStrat(strSysTime[0]), getNowDay()); comboYear.setSelectedIndex(getNowYear() – 1900); comboMonth.setSelectedIndex(getNowMonth()); } public void setDate(int move) { // 將時間設置為選中的年月增加move個月之後的時間 setSysTime(getYear(), getMonth() + move); getSysTimeInfo(); setDayNull(); getDay(getMonthDays(getYear(), getMonth() + move – 1), getMonthDays( getYear(), getMonth() + move), weekStrat(strSysTime[0]), -1); if (move != 0) { if (getMonth() == 0 move 0) { move = 11; comboYear.setSelectedIndex(getYear() – 1901); } else if (getMonth() == 11 move 0) { move = -11; comboYear.setSelectedIndex(getYear() – 1899); } else { comboYear.setSelectedIndex(getYear() – 1900); } comboMonth.setSelectedIndex(getMonth() + move); } } public void setSysTime(int year, int month) { gregorianCalendar.set(year, month, 1); } public int getNowYear() { return Integer.parseInt(strSysNowTime[5]); } public int getNowDay() { return Integer.parseInt(strSysNowTime[2]); } public int getYear() { return comboYear.getSelectedIndex() + 1900; } public int getMonth() { return comboMonth.getSelectedIndex(); } public void setDayNull() { for (int d = 0; d 42; d++) { buttonDay[d].setText(“”); } } public void getDay(int lastMonDays, int monthDays, int startWeek, int day) { // 設置日期顏色並打印 for (int d = 0; d startWeek + 1; d++) { buttonDay[d].setForeground(Color.GRAY); buttonDay[d].setText((lastMonDays – startWeek) + d + 1 + “”); } for (int d = startWeek; d startWeek + monthDays; d++) { if ((d – startWeek + 1) == day) { buttonDay[d].setForeground(Color.blue); } else if (d % 7 == 0 || d % 7 == 6) { buttonDay[d].setForeground(Color.RED); } else { buttonDay[d].setForeground(Color.BLACK); } buttonDay[d].setText(d – startWeek + 1 + “”); } for (int d = monthDays + startWeek; d 42; d++) { buttonDay[d].setForeground(Color.GRAY); buttonDay[d].setText(d – (monthDays + startWeek) + 1 + “”); } } public int getMonthDays(int year, int month) { // 返回year年month月的天數 switch (month) { case 3: case 5: case 8: case 10: return 30; case 1: if (gregorianCalendar.isLeapYear(year)) { return 29; } else { return 28; } default: return 31; } }}

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寫個日曆程序怎麼寫,請給出詳細步驟,謝謝

隨便做了一個,其實一樓網友說的判斷哪些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編寫日曆

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

}

}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/293230.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-26 13:13
下一篇 2024-12-26 13:13

相關推薦

  • Python腳本控制其他軟件

    Python作為一種簡單易學、功能強大的腳本語言,具有廣泛的應用領域,在自動化測試、Web開發、數據挖掘等領域都得到了廣泛的應用。其中,Python腳本控制其他軟件也是Python…

    編程 2025-04-29
  • Python數據處理課程設計

    本文將從多個方面對Python數據處理課程設計進行詳細闡述,包括數據讀取、數據清洗、數據分析和數據可視化四個方面。通過本文的學習,讀者將能夠了解使用Python進行數據處理的基本知…

    編程 2025-04-29
  • Shell腳本與Python腳本的區別

    本文將從多個方面對Shell腳本與Python腳本的區別做詳細的闡述。 一、語法差異 Shell腳本和Python腳本的語法存在明顯差異。 Shell腳本是一種基於字符命令行的語言…

    編程 2025-04-29
  • Python自動化運維腳本

    Python自動化運維腳本是使用Python編寫的代碼,可以幫助管理員自動化執行繁瑣、重複的操作任務。通過Python自動化運維腳本,管理員可以在更短的時間內完成工作,提高工作效率…

    編程 2025-04-28
  • 使用Python圖書館搶座腳本的完整步驟

    本文將從多個方面詳細介紹如何使用Python編寫圖書館的座位搶佔腳本,並幫助您快速了解如何自動搶佔圖書館的座位,並實現您的學習計劃。 一、開發環境搭建 首先,我們需要安裝Pytho…

    編程 2025-04-28
  • ArcGIS的Python腳本需要主函數嗎?

    是的,ArcGIS的Python腳本需要主函數,主函數是Python腳本的入口和起點,沒有主函數腳本無法運行。 一、主函數的作用 在Python腳本中,主函數是代碼的入口,所有的代…

    編程 2025-04-28
  • Python監控腳本開發指南

    本文將為大家介紹Python編寫監控腳本的方法和技巧,幫助大家更好地了解監控腳本在項目中的應用。 一、監控腳本概述 監控腳本可以作為一個重要的工具來監控服務器狀態,包括CPU、內存…

    編程 2025-04-27
  • Python課程設計題目用法介紹

    Python是一門高級、面向對象的編程語言,廣泛應用於Web應用程序開發、人工智能、數據科學、自動化測試等領域。Python基礎課程學習是每個Python學習者必須經歷的階段,而P…

    編程 2025-04-27
  • 如何使用JS調用Python腳本

    本文將詳細介紹通過JS調用Python腳本的方法,包括使用Node.js、Python shell、child_process等三種方法,以及在Web應用中的應用。 一、使用Nod…

    編程 2025-04-27
  • Django項目中執行Python腳本

    本文將闡述在Django項目中如何執行Python腳本以及執行腳本的幾種方式。 一、subprocess模塊執行Python腳本 subprocess模塊提供了一個簡單的接口用於創…

    編程 2025-04-27

發表回復

登錄後才能評論