導航:首頁 > 編程語言 > java創建日歷

java創建日歷

發布時間:2024-07-16 03:50:21

java日歷代碼,怎麼做

import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.border.LineBorder;

/**

* @company:NEUSOFT
* @Title:日期選擇控制項
* @Description:在原有基礎上修改了以下內容:
* 1. 將容器由Frame改為了Dialog,以便在基於對話框的程序中也能夠使用
* 2. 將最小日期由1980改為了1950,考慮到目前球員的出生日期可能早於1980年
* 3. 將初始顯示格式設置為 yyyy年MM月dd日 格式,原有的小時去掉了,不適合於出生日期欄位
*/
public class DateChooserJButton extends JButton {

private DateChooser dateChooser = null;

private String preLabel = "";

public DateChooserJButton() {
this(getNowDate());
}

public DateChooserJButton(SimpleDateFormat df, String dateString) {
this();
setText(df, dateString);
}

public DateChooserJButton(Date date) {
this("", date);
}

public DateChooserJButton(String preLabel, Date date) {
if (preLabel != null)
this.preLabel = preLabel;
setDate(date);
setBorder(null);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (dateChooser == null)
dateChooser = new DateChooser();
Point p = getLocationOnScreen();
p.y = p.y + 30;
dateChooser.showDateChooser(p);
}
});
}

private static Date getNowDate() {
return Calendar.getInstance().getTime();
}

private static SimpleDateFormat getDefaultDateFormat() {
return new SimpleDateFormat("yyyy年MM月dd日");
}

// 覆蓋父類的方法
public void setText(String s) {
Date date;
try {
date = getDefaultDateFormat().parse(s);
} catch (ParseException e) {
date = getNowDate();
}
setDate(date);
}

public void setText(SimpleDateFormat df, String s) {
Date date;
try {
date = df.parse(s);
} catch (ParseException e) {
date = getNowDate();
}
setDate(date);
}

public void setDate(Date date) {
super.setText(preLabel + getDefaultDateFormat().format(date));
}

public Date getDate() {
String dateString = this.getText().substring(preLabel.length());
try {
return getDefaultDateFormat().parse(dateString);
} catch (ParseException e) {
return getNowDate();
}

}

public String getDateString()
{
Date birth =getDate();
DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
return formatDate.format(birth).toString();

//return this.getText().substring(preLabel.length());
}

// 覆蓋父類的方法使之無效
//public void addActionListener(ActionListener listener) {
//}

private class DateChooser extends JPanel implements ActionListener,
ChangeListener {
int startYear = 1950; // 默認【最小】顯示年份

int lastYear = 2050; // 默認【最大】顯示年份

int width = 200; // 界面寬度

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; // RoundBox文字色

Color rbBorderColor = Color.red; // RoundBox邊框色

Color rbButtonColor = Color.pink; // RoundBox按鈕色

Color rbBtFontColor = Color.red; // RoundBox按鈕文字色

JDialog dialog;

JSpinner yearSpin;

JSpinner monthSpin;

JSpinner hourSpin;

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

DateChooser() {

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() {
Calendar c = getCalendar();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH) + 1;
int currentHour = c.get(Calendar.HOUR_OF_DAY);

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

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.RIGHT);
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.RIGHT);
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;
result.add(numberButton);
actionCommandId++;
}

return result;
}

private JDialog createDialog(JDialog 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;
}

void showDateChooser(Point position) {
JDialog owner = (JDialog) SwingUtilities
.getWindowAncestor(DateChooserJButton.this);
if (dialog == null || dialog.getOwner() != owner)
dialog = createDialog(owner);
dialog.setLocation(getAppropriateLocation(owner, position));
flushWeekAndDay();
dialog.setVisible(true);
}

Point getAppropriateLocation(JDialog 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;

}

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 void dayColorUpdate(boolean isOldDay) {
Calendar c = getCalendar();
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() {
Calendar c = getCalendar();
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();
Calendar c = getCalendar();
if (source.getName().equals("Hour")) {
c.set(Calendar.HOUR_OF_DAY, getSelectedHour());
setDate(c.getTime());
return;
}

dayColorUpdate(true);

if (source.getName().equals("Year"))
c.set(Calendar.YEAR, getSelectedYear());
else
// (source.getName().equals("Month"))
c.set(Calendar.MONTH, getSelectedMonth() - 1);
setDate(c.getTime());
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());
Calendar c = getCalendar();
c.set(Calendar.DAY_OF_MONTH, newDay);
setDate(c.getTime());
}

}

}

這是一個專門的選日期的類 ,你看看完了調用就行了

㈡ 用java圖形用戶界面實現: 編寫一個日歷程序,能實現顯示日歷等簡單功能。

||import javax.swing.JOptionPane;

public class NewClass{
public static void main(String[] args){
int year,month;
Calender cal=new Calender(2008,10);
cal.showCalender();
year=Integer.parseInt(JOptionPane.showInputDialog("Year:"));
month=Integer.parseInt(JOptionPane.showInputDialog("Month:"));
cal.setYear(year);
cal.setMonth(month);
cal.showCalender();
}
}

class Calender{
private int year,month;
public Calender(){
year=0;
month=1;
}
public Calender(int year){
this.year=year;
month=1;
}
public Calender(int year,int month){
this.year=year;
if(month>12)
this.month=month%12;
else
this.month=month;
}
public void setYear(int year){
this.year=year;
}
public void setMonth(int month){
if(month>12)
this.month=month%12;
else
this.month=month;
}
private int dayOfMonth(){
int days=0;
switch(month){
case 1:days=31;break;
case 2:{
if(((year%4==0)&&(year%100!=0))||(year%400==0))
days=29;
else
days=28;
break;
}
case 3:days=31;break;
case 4:days=30;break;
case 5:days=31;break;
case 6:days=30;break;
case 7:days=31;break;
case 8:days=31;break;
case 9:days=30;break;
case 10:days=31;break;
case 11:days=30;break;
case 12:days=31;break;
default:
days=0;
}
return days;
}
private int dayOfWeek(){
int Y=year;
int M=month;
int D=1;
int A;
A = Y>0?(5+(Y+1)+(Y-1)/4-(Y-1)/100+(Y-1)/400)%7:(5+Y+Y/4-Y/100+Y/400)%7;
A = M>2?(A+2*(M+1)+3*(M+1)/5)%7:(A+2*(M+2)+3*(M+2)/5)%7;
if (((Y%4 == 0 && Y%100 != 0)|| Y%400 == 0) && M>2) A =(A+1)%7;
A=(A+D)%7;
return A;
}
public void showCalender(){
String str=new String();
str=" ";
str+=year+"年"+month+"月";
str+="\n\n";
str+="日 一 二 三 四 五 六\n";
int week=this.dayOfWeek();
for(int i=0,j=1;i<7;i++){
if(i<week)
str+=" ";
else{
str+=" "+j+" ";
j++;
}
}
str+="\n";
end:
for(int i=7-week+1;i<=this.dayOfMonth();){
for(int j=0;j<7;j++){
if(i<10)
str+=" "+i+" ";
else
str+=i+" ";
i++;
if(i>this.dayOfMonth())
break end;
}
str+="\n";
}
JOptionPane.showMessageDialog(null,str);

}
}

㈢ java如何創建一個指定的日期對象

第一個問題:
這有好幾種做法都可以實現:
1.new一個java.util.Date對象,調用它的setYear、setMonth等等方法,設置你要的年月日。不過這種做法不推薦,因為setYear等方法已經過時了。
2.new一個java.util.SimpleDateFormat類的實例,構造方法可以指定日期格式,例如yyyy-MM-dd,其中yyyy表示四位年份,MM表示兩位月份,dd表示兩位日期。然後通過調用這個SimpleDateFormat實例的parse方法可以解析獲得指定日期的Date對象。
代碼示例:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2014-03-02");
3.通過java.util.Calendar類的靜態方法getInstance()獲得一個日歷類實例,然後調用此實例的set(int year, int month, int date)
設置日歷欄位 YEAR、MONTH 和 DAY_OF_MONTH 的值,然後調用實例的getTime()方法可以獲得指定日期的Date對象

第二個問題:
參考上一個問題的第3種做法,Calendar.getInstance()獲得的是當前時刻的日歷實例對象,調用此實例對象的setLenient(false)設置日歷解釋為寬松模式,然後再通過roll(int field, boolean up)方法在給定的時間欄位上添加或減去(上/下)單個時間單元(例如你要的「一個月」時間單月),最後通過getTime()方法獲得Date對象。

這兩個問題都是很簡單的,你找份JDK API文檔看看就可以找到辦法了,自己多看多想會更好。

㈣ 用JAVA做日歷

import java.util.*;

public class test {
public static void main( String[] args ) {
String[] wd= { "日", "一", "二", "三", "四", "五", "六" };
Scanner s = new Scanner(System.in);
P("請輸入要查詢的年份:");
int y = s.nextInt();
P("請輸入月份:");
int m = s.nextInt();
if(y < 2000 || y > 2010) {
P("不在查詢范圍之內!");
return;
}

GregorianCalendar g = new GregorianCalendar( y, m-1, 1 );

P( "\n星期\t" );
for ( int j = 0; j < wd.length; ++j )
P( wd[j] + "\t" );
P();
for ( int j = 0; j < g.get( Calendar.DAY_OF_WEEK ); ++j )
P( "\t" );
int thisMonth = g.get( Calendar.MONTH );
for ( int j = 1; j <= 31; ++j ) {
int d = g.get( Calendar.DAY_OF_MONTH );
P( d + "\t" );
if ( g.get( Calendar.DAY_OF_WEEK ) == 7 ) {
P("\n\t");
}
g.add( Calendar.DAY_OF_YEAR, 1 );
if ( g.get( Calendar.MONDAY ) != thisMonth ) {
P("\n\n");
break;
}
}
}

static void P( String s )
{
System.out.print( s );
}
static void P()
{
System.out.println();
}
}

㈤ 怎樣用java編寫日歷

Java編寫日歷代碼:

importjava.util.Scanner;
publicclassWan{publicstaticvoidmain(String[]args)
{
Scannername=newScanner(System.in);
System.out.print("請輸入要查詢的年份:");
intyear=name.nextInt();
System.out.print("請輸入該年的月份");
intmonth=name.nextInt();
}//累加該年至輸入的月份天數
//比如輸入2009年的3月分
//那就累加2009年的1月至
3月1號的總天數
publicvoidsumDay(intyear,intmonth)
{
intday=0;
intsumDay=0;
for(inti=1;i<=month;i++){switch(i)
{
case1:
case3:
case5:
case7:
case8:
case10:
case12:
day=31;
break;
case2:
if(year%4==0||year%400==0&&year%100!=0)
{day=29;}
else{day=28;}
break;
default:day=30;}
//最後一個月份不要累加因為我們只是要算到該月的一號就可以了
if(i<month){sumDay+=day;}}
//累加2000年到該年的一月一號天數
for(inti=2000;i<year;i++)
{if(i%4==0||i%400==0&&i%100!=0)
{sumDay+=366;}else{sumDay+=365;}}
//求該月一號為星期幾
intweek=sumDay%7+1;if(week==7){week=0;}}
publicvoidfomatDate(intweek,intday)
{
intg=0;for(inti=0;i<week;i++)
{System.out.print(" ");}
for(inti=1;i<=day;i++){System.out.print(i+" ");
g=week+i;if(g%7==0){System.out.println();}
}
}
}
閱讀全文

與java創建日歷相關的資料

熱點內容
重要文件密碼更換周期是多少 瀏覽:871
mac上用jsp寫一個網頁 瀏覽:6
word標准行間距 瀏覽:90
sw如何查看文件路徑 瀏覽:329
jsp判斷null 瀏覽:28
系統apk圖標修改工具下載 瀏覽:703
jsp模型 瀏覽:431
承德貨車運輸哪個app好 瀏覽:907
華為5x書簽文件夾路徑 瀏覽:120
滑動t檢驗法程序 瀏覽:940
java百分數格式化 瀏覽:911
數據分析怎麼看市場 瀏覽:993
魔獸聯盟160升級攻略 瀏覽:234
iphone6plus直接購買 瀏覽:386
電腦升級後舊文件備份在哪裡的 瀏覽:236
怎麼禁止電腦文件到u盤外泄 瀏覽:217
pc端如何用modbustcp編程 瀏覽:336
富士xp142怎麼編程 瀏覽:481
導航卡的數據是從哪裡來的 瀏覽:168
為什麼桌面會顯示c盤某某文件 瀏覽:745

友情鏈接