大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
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类,放在同一个包里。经测试可以运行。
//Start.java
import java.awt.*;
import javax.swing.*;
class Start{
public static void main(String [] args){
DateFrame frame=new DateFrame();
frame.setLocationRelativeTo(frame);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//DateInfo.java
import java.util.*;
public class DateInfo{
private int mYear, mMonth;
private int mDayOfMonth, mFristWeek;
public DateInfo(int year, int month) throws DateException{
mYear = year;
if (month 0 || month 12){
throw (new DateException());
}
mMonth = month;
mDayOfMonth = getDayOfMonth(mYear, mMonth);
mFristWeek = getFristWeek(mYear, mMonth);
}
private int getDayOfMonth(int year, int month){
int[][] ary = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
return (ary[isLeapYear(year)][month]);
}
private int isLeapYear(int year){
if (year % 4 == 0 year % 100 != 0 ||year % 400 == 0){
return (1);
}
else{
return (0);
}
}
private int getFristWeek(int year, int month){
java.util.Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, 1);
return (cal.get(Calendar.DAY_OF_WEEK) - 1);
}
public String toString(){
String str;
str = "\t\t" + mYear + "年" + mMonth + "月\n";
str += "日\t一\t二\t三\t四\t五\t六\n";
int i;
for (i = 1; i = mFristWeek; i++){
str += " \t";
}
for (int j = 1; j = mDayOfMonth; j++, i++){
str +=j+"\t" ;
if (i % 7 == 0){
str += "\n";
}
}
return (str);
}
}
//DateFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;
class DateFrame extends JFrame implements Runnable{
Calendar date=Calendar.getInstance();
String[] str={"1","2","3","4","5","6","7","8","9","10","11","12"};
JLabel lblYear=new JLabel("年 ");
JLabel lblMonth=new JLabel("月 ");
JLabel lblDate=new JLabel("现在的时间是:");
JLabel lblShowDate=new JLabel();
// javax.swing.JTextField trxt =new JTextField(10);
// trxt.setHorizontalAlignment(JTextField.RIGHT); //设置文本从右边输入
JComboBox cboMonth=new JComboBox(str);
JComboBox cboYear=new JComboBox();
JTextArea txaShow=new JTextArea();
JPanel pnlNorth=new JPanel();
JPanel pnlSOUTH=new JPanel();
JButton btnShow=new JButton("显示");
JButton btnClose=new JButton("关闭");
JScrollPane jsp=new JScrollPane(txaShow);
Container c=this.getContentPane();
public DateFrame(){
Thread thread=new Thread(this);
thread.start();
this.setTitle("玩玩日历拉!!!");
this.setSize(300,260);
for (int i = 1990; i=2025; i++) {
cboYear.addItem(""+i);
}
cboYear.setSelectedItem(""+(date.get(Calendar.YEAR)));
cboMonth.setSelectedItem(""+(date.get(Calendar.MONTH)+1));
pnlNorth.add(cboYear);
txaShow.setTabSize(4); //设置tab键的距离
txaShow.setForeground(Color.GREEN);
pnlNorth.add(lblYear);
pnlNorth.add(cboMonth);
pnlNorth.add(lblMonth);
pnlNorth.add(lblDate);
pnlNorth.add(lblShowDate);
c.add(pnlNorth,BorderLayout.NORTH);
c.add(jsp);
pnlSOUTH.add(btnShow);
pnlSOUTH.add(btnClose);
c.add(pnlSOUTH,BorderLayout.SOUTH);
btnShow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int year=Integer.parseInt((String)cboYear.getSelectedItem());
int month=Integer.parseInt((String)cboMonth.getSelectedItem());
try {
DateInfo date=new DateInfo(year,month);
txaShow.setText(""+date);
}
catch (DateException ex) {
ex.printStackTrace();
}
}
});
btnClose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public void run(){
try {
while(true){
Thread.sleep(1000);
int hour=date.get(Calendar.HOUR);
int minute=date.get(Calendar.MINUTE);
int second=date.get(Calendar.SECOND);
String str=hour+":"+minute+":"+second;
lblShowDate.setText(str);
//this.repaint();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//DateException.java
public class DateException extends Exception{
public DateException(){
super("日期数据不合法.");
}
}
以下是两个类,请楼主分别存成两个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);
}
}
import java.util.Scanner; public class Wan{ public static void main(String[] args){ Scanner name = new Scanner(System.in); System.out.print("请输入要查询的年份:"); int year = name.nextInt(); System.out.print("请输入该年的月份"); int month = name.nextInt(); } //累加 该年至输入的月份 天数 //比如 输入2009年的 3月分 // 那就累加 2009年的1月至 3月1号的总天数 public void sumDay(int year,int month){ int day = 0; int sumDay = 0; for(int i = 1;i=month;i++){ switch(i){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 2: 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(int i = 2000;iyear;i++){ if( i % 4 == 0 || i %400== 0 i % 100 != 0){ sumDay += 366; }else{ sumDay += 365; } } //求该月一号为星期几 int week = sumDay % 7 +1; if(week == 7){ week = 0; } } public void fomatDate(int week,int day){ int g = 0; for(int i = 0;iweek;i++){ System.out.print("\t"); } for(int i = 1;i=day;i++){ System.out.print(i+"\t"); g = week + i; if(g % 7 == 0){ System.out.println(); } } } } 给点分哈 写得好累