导航:首页 > 编程语言 > 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创建日历相关的资料

热点内容
企业微信电脑版怎么无法接受文件 浏览:968
微信个人相册怎么隐藏 浏览:368
上传文件时怎么获取文件全路径 浏览:955
linuxjs读取文件 浏览:104
exe后缀的pdf文件 浏览:381
win8升级到专业版 浏览:487
快图浏览quickpiciphone 浏览:847
app线稿图需要哪些要求 浏览:752
java只能输入汉字 浏览:630
java定义char 浏览:133
excel2007插入压缩文件 浏览:70
怎么设定自己公司的网站 浏览:324
如何在办公软件上直接复制文件 浏览:939
c语言程序设计矩阵运算 浏览:894
影响网络质量因素有哪些 浏览:587
最新win10秘钥在线激活 浏览:192
cad导入su8文件无法使用 浏览:828
怎么做编程入门 浏览:851
用织梦建手机网站 浏览:38
灌南数控编程怎么学 浏览:957

友情链接