新网创想网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
也不知道你具体需求是什么,以前改过一个日历程序,一共四个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("日期数据不合法.");
}
}
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(); } } } } 给点分哈 写得好累
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();
}
}
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());
}
}
}
这是一个专门的选日期的类 ,你看看完了调用就行了