Swing 写的日期时间组件

在网上收集的swing时间组件完善了一下,日期上下按钮可以点击,闰年平年判断,月份是多少天自动更新改变。希望大家继续完善。

MainApp

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
 

public class MainApp  extends JFrame {

	
	 public static int x=0;
	 public static int y=0;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 
		 JFrame jf = new JFrame();
		 JPanel tabPanel = new JPanel();
		 JButton timeButton = new DataChooser();
		 tabPanel.add(timeButton);
		 jf.add(tabPanel);
		 jf.setBounds(350, 200, 500, 400);
		 jf.setVisible(true);
		 jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		 jf.addWindowListener(new WindowAdapter(){
	                       public void windowClosing(WindowEvent e){
	                         int n=JOptionPane.showConfirmDialog(null,"确认退出吗?","确认对话框",
	                                                  JOptionPane.YES_NO_OPTION );
	                         if(n==JOptionPane.YES_OPTION)  
	                            {System.exit(0);}
	                         return;
	                       }});
	       
	      jf.setEnabled(true);
	}
 
	 
}

DataChooser

 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 *
 * Allen 收集网上靠谱的例子,修改后的Swing日期
 * 时间选择器,因为修改时间匆忙,希望有时间的朋友继续改进。
 * 例子原作者:zjw
 * 修改/完善:Allen ---swing时间组件完善时间2013.06.20

 */
public class DataChooser extends JButton {

    private DateChooser dateChooser = null;
    private String preLabel = "";
    private String originalText = null;
    private SimpleDateFormat sdf = null;
    public static boolean tFlag = true;
    public static Timer accetimer;
    public static String datatimerName = "";
 
    private   long t_start =0; 
    private  long t_end =0; 
    private  long ss =0; 
    
    public static int currAccYear = 0;
    public static int currAccMont = 0;
    public static int currAccDay = 0;
    
    public DataChooser() {
        this(getNowDate());
        //this.datatimerName = datatimerName;
    }
 

	public DataChooser(String dateString) {
        this();
        setText(getDefaultDateFormat(), dateString);
        //保存原始是日期时间
        initOriginalText(dateString);
    }

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

        //记忆当前的日期格式化器
        this.sdf = df;

        //记忆原始日期时间
        Date originalDate = null;
        try {
            originalDate = df.parse(dateString);
        } catch (ParseException ex) {
            originalDate = getNowDate();
        }
        initOriginalText(originalDate);
    }

    public DataChooser(Date date) {
        this("", date);
        //记忆原始日期时间
        initOriginalText(date);
    }

    public DataChooser(String preLabel, Date date) {
        if (preLabel != null) {
            this.preLabel = preLabel;
        }
        setDate(date);
        //记忆原始是日期时间
        initOriginalText(date);

        //setBorder(null);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        super.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (dateChooser == null) {
                    dateChooser = new DateChooser();
                    tFlag = false;
                }
                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 HH:mm:ss");
    }

    /**
     * 得到当前使用的日期格式化器
     * @return 日期格式化器
     */
    public SimpleDateFormat getCurrentSimpleDateFormat(){
        if(this.sdf != null){
            return sdf;
        }else{
            return getDefaultDateFormat();
        }
    }


    //保存原始是日期时间
    private void initOriginalText(String dateString) {
        this.originalText = dateString;
    }

    //保存原始是日期时间
    private void initOriginalText(Date date) {
        this.originalText = preLabel + getDefaultDateFormat().format(date);
        
        
    }

    /** 
     * 得到当前记忆的原始日期时间
     * @return 当前记忆的原始日期时间(未修改前的日期时间)
     */
    public String getOriginalText() {
        return originalText;
    }

    // 覆盖父类的方法
    @Override
    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) {
    	if(tFlag){
    		 
    		super.setText("时间组件");
    	}else{
    		
    		super.setText(preLabel + getDefaultDateFormat().format(date));
    	}
        
    }

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

    /**  
     * 覆盖父类的方法使之无效
     * @param listener 响应监听器
     */
    @Override
    public void addActionListener(ActionListener listener) {
    }

    /**
     * 内部类,主要是定义一个JPanel,然后把日历相关的所有内容填入本JPanel,
     * 然后再创建一个JDialog,把本内部类定义的JPanel放入JDialog的内容区
     */
    private class DateChooser extends JPanel implements ActionListener, ChangeListener {

        int startYear = 1980; // 默认【最小】显示年份
        int lastYear = 2050; // 默认【最大】显示年份
        int width = 390; // 界面宽度
        int height = 210; // 界面高度
        Color backGroundColor = Color.gray; // 底色
        // 月历表格配色----------------//
        Color palletTableColor = Color.white; // 日历表底色
        Color todayBackColor = Color.GREEN; // 今天背景色
        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按钮文字色
        /** 点击DateChooserButton时弹出的对话框,日历内容在这个对话框内 */
        JDialog dialog;
        JSpinner yearSpin;
        JSpinner monthSpin;
        JSpinner daySpin;
        JSpinner hourSpin;
        JSpinner minuteSpin;
        JSpinner secondSpin;
        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);
            JPanel buttonBarPanel = createButtonBarPanel();
            this.add(buttonBarPanel, java.awt.BorderLayout.SOUTH);
        }

        private JPanel createYearAndMonthPanal() {
            Calendar c = getCalendar();
            int currentYear = c.get(Calendar.YEAR);
            int currentMonth = c.get(Calendar.MONTH) + 1;
            int currentDay = c.get(Calendar.DATE );
            int currentHour = c.get(Calendar.HOUR_OF_DAY);
            int currentMinute = c.get(Calendar.MINUTE);
            int currentSecond = c.get(Calendar.SECOND);

            currAccYear = currentYear;
            currAccMont = currentMonth;
            currAccDay = currentDay;
            
            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);
            
            String dataYMD = "";
            if(currentMonth<10){
            	 
            	 if(currentDay<10){
            		 dataYMD = currentYear+"-0"+currentMonth+"-0"+currentDay;
            	 }
            	 else{
            		 
            		 dataYMD = currentYear+"-0"+currentMonth+"-"+currentDay;
            	 }
            	
            	
            }else{
            	
            	 if(currentDay<10){
            		 dataYMD = currentYear+"-"+currentMonth+"-0"+currentDay;
            	 }
            	 else{
            		 
            		 dataYMD = currentYear+"-"+currentMonth+"-"+currentDay;
            	 }
            }
            String lastDay = getEndDateOfMonth(dataYMD);
            lastDay = lastDay.substring(8, lastDay.length());
     
           
            daySpin = new JSpinner(new SpinnerNumberModel(currentDay, 1,Integer.parseInt(lastDay), 1));
            daySpin.setPreferredSize(new Dimension(35, 20));
            daySpin.setName("Day");
            daySpin.addChangeListener(this);
           // daySpin.setEnabled(false);
          //  daySpin.setToolTipText("请下下面的日历面板中进行选择哪一天!");
            daySpin.addChangeListener(this);
            result.add(daySpin);
            
            JLabel dayLabel = new JLabel("日");
            dayLabel.setForeground(controlTextColor);
            result.add(dayLabel);

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

            minuteSpin = new JSpinner(new SpinnerNumberModel(currentMinute, 0, 59, 1));
            minuteSpin.setPreferredSize(new Dimension(35, 20));
            minuteSpin.setName("Minute");
            minuteSpin.addChangeListener(this);
            result.add(minuteSpin);

            JLabel minuteLabel = new JLabel("分");
            hourLabel.setForeground(controlTextColor);
            result.add(minuteLabel);

            secondSpin = new JSpinner(new SpinnerNumberModel(currentSecond, 0, 59, 1));
            secondSpin.setPreferredSize(new Dimension(35, 20));
            secondSpin.setName("Second");
            secondSpin.addChangeListener(this);
            result.add(secondSpin);

            JLabel secondLabel = new JLabel("秒");
            hourLabel.setForeground(controlTextColor);
            result.add(secondLabel);

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

        /** 得到DateChooserButton的当前text,本方法是为按钮事件匿名类准备的。 */
        public String getTextOfDateChooserButton() {
            return getText();
        }

        /** 恢复DateChooserButton的原始日期时间text,本方法是为按钮事件匿名类准备的。 */
        public void restoreTheOriginalDate() {
        	tFlag = true;
            String originalText = getOriginalText();
            setText(originalText);
        }

        private JPanel createButtonBarPanel() {
            JPanel panel = new JPanel();
            panel.setLayout(new java.awt.GridLayout(1, 2));

            JButton ok = new JButton("确定");
            ok.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    //记忆原始日期时间
                    initOriginalText(getTextOfDateChooserButton());
                    //隐藏日历对话框
                    String seleTime = getTextOfDateChooserButton();
                    Date currentTime = new Date();
                    SimpleDateFormat sdfor = new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateString = sdfor.format(currentTime);
                    Date dsele = null;
                    boolean flag =false;
					try {
				    if(seleTime.equals("时间组件")){
							 JOptionPane.showMessageDialog(null,"你设置的时间已经过期!");
							 return;
								
					}	
			 
                    else{
						 dsele = sdfor.parse(seleTime);
						 Date dcurr = sdfor.parse(dateString);
	                     flag = dsele.before(dcurr);
	                     if(flag){
	                    	 JOptionPane.showMessageDialog(null,"你设置的时间已经过期!");
							return;
						 }
						 long   startT=sdfor.parse(dateString).getTime();  
		                 long   endT=sdfor.parse(seleTime).getTime();  
		                
		                 doTimer(startT,endT);
						 dialog.setVisible(false);
					}
					
					} catch (ParseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					
                   
                }
            });
            panel.add(ok);

            JButton cancel = new JButton("取消");
            cancel.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    //恢复原始的日期时间
                    restoreTheOriginalDate();
                    //隐藏日历对话框
                    dialog.setVisible(false);
                }
            });

            panel.add(cancel);
            return panel;
        }
        
        private JDialog createDialog(Frame 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) {
            Frame owner = (Frame) SwingUtilities.getWindowAncestor(DataChooser.this);
            if (dialog == null || dialog.getOwner() != owner) {
                dialog = createDialog(owner);
            }
            dialog.setLocation(getAppropriateLocation(owner, position));
            flushWeekAndDay();
            dialog.setVisible(true);
        }

        Point getAppropriateLocation(Frame 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 getSelectedDay() {
            return ((Integer) daySpin.getValue()).intValue();
        }

        private int getSelectedHour() {
            return ((Integer) hourSpin.getValue()).intValue();
        }

        private int getSelectedMinite() {
            return ((Integer) minuteSpin.getValue()).intValue();
        }

        private int getSelectedSecond() {
            return ((Integer) secondSpin.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);
        }

        /**
         * 选择日期时的响应事件
         */
        @Override
        public void stateChanged(ChangeEvent e) {
        	
            Calendar cc = Calendar.getInstance();
            JSpinner source = (JSpinner) e.getSource();
            Calendar c = getCalendar();
            if (source.getName().equals("Hour")) {
                c.set(Calendar.HOUR_OF_DAY, getSelectedHour());
                setDate(c.getTime());
                return;
            }
            if (source.getName().equals("Minute")) {
                c.set(Calendar.MINUTE, getSelectedMinite());
                setDate(c.getTime());
                return;
            }
            if (source.getName().equals("Second")) {
                c.set(Calendar.SECOND, getSelectedSecond());
                setDate(c.getTime());
                return;
            }
            if(e.getSource()==monthSpin){
            	 
            	currAccYear =getSelectedYear();
            	currAccMont = getSelectedMonth();
            	currAccDay= getSelectedDay();
            	//daySpin = new SpinnerNumberModel(25, 1,20, 1));
            	 String dataYMD = "";
            	 
            	 if(currAccMont<10){
                	 
                	 if(currAccDay<10){
                		 dataYMD = currAccYear+"-0"+currAccMont+"-0"+currAccDay;
                	 }
                	 else{
                		 
                		 dataYMD = currAccYear+"-0"+currAccMont+"-"+currAccDay;
                	 }
                	
                	
                }else{
                	
                	 if(currAccDay<10){
                		 dataYMD = currAccYear+"-"+currAccMont+"-0"+currAccDay;
                	 }
                	 else{
                		 
                		 dataYMD = currAccYear+"-"+currAccMont+"-"+currAccDay;
                	 }
                }
                 String lastDay = getEndDateOfMonth(dataYMD);
                 lastDay = lastDay.substring(8, lastDay.length());
            	 int currentDay = c.get(Calendar.DATE );
            	 
            	 if(Integer.parseInt(lastDay)==29){
            		 
            		 if(currAccDay>=29){
            			 daySpin.setModel(new SpinnerNumberModel(29, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 else{
            			 daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 
            	 }
            	 else if(Integer.parseInt(lastDay)==28){
            		 
            		 if(currAccDay>=28){
            			 daySpin.setModel(new SpinnerNumberModel(28, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 else{
            			 daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 
            	 }
                 else if(Integer.parseInt(lastDay)==30){
            		 
                	 if(currAccDay>1){
            			 daySpin.setModel(new SpinnerNumberModel(currAccDay-1, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 else{
            		     daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            		 }
            	 }
            	 else{
            	  daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            	 }
            
            }
            
            if(e.getSource()==yearSpin){
            	
            	currAccYear =getSelectedYear();
            	currAccMont = getSelectedMonth();
            	currAccDay= getSelectedDay();
            	//daySpin = new SpinnerNumberModel(25, 1,20, 1));
            	 String dataYMD = "";
            	 
            	 if(currAccMont<10){
                	 
                	 if(currAccDay<10){
                		 dataYMD = currAccYear+"-0"+currAccMont+"-0"+currAccDay;
                	 }
                	 else{
                		 
                		 dataYMD = currAccYear+"-0"+currAccMont+"-"+currAccDay;
                	 }
                	
                	
                }else{
                	
                	 if(currAccDay<10){
                		 dataYMD = currAccYear+"-"+currAccMont+"-0"+currAccDay;
                	 }
                	 else{
                		 
                		 dataYMD = currAccYear+"-"+currAccMont+"-"+currAccDay;
                	 }
                }
                 String lastDay = getEndDateOfMonth(dataYMD);
                 lastDay = lastDay.substring(8, lastDay.length());
            	 int currentDay = c.get(Calendar.DATE );
                 if(Integer.parseInt(lastDay)==29){
            		 
            		 if(currAccDay>=29){
            			 daySpin.setModel(new SpinnerNumberModel(29, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 else{
            			 daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 
            	 }
            	 else if(Integer.parseInt(lastDay)==28){
            		 
            		 if(currAccDay>=28){
            			 daySpin.setModel(new SpinnerNumberModel(28, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 else{
            			 daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 
            	 }
            	 else if(Integer.parseInt(lastDay)==30){
            		 if(currAccDay>1){
            			 daySpin.setModel(new SpinnerNumberModel(currAccDay-1, 1,Integer.parseInt(lastDay), 1));
            		 }
            		 else{
            		     daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            		 }
            	 }
            	 else{
            	  daySpin.setModel(new SpinnerNumberModel(currAccDay, 1,Integer.parseInt(lastDay), 1));
            	 }
                 
            
            }
            
            
            
            dayColorUpdate(true);

            if (source.getName().equals("Year")) {
                c.set(Calendar.YEAR, getSelectedYear());
            } 
            else if (source.getName().equals("Month")) {
                c.set(Calendar.MONTH, getSelectedMonth() - 1);
            }
            else if (source.getName().equals("Day")) {
                c.set(Calendar.DATE,getSelectedDay() );
            }  
            setDate(c.getTime());
            flushWeekAndDay();
            
        }

        /**
         * 选择日期时的响应事件
         */
        @Override
        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());
            //把daySpin中的值也变了
            daySpin.setValue(Integer.valueOf(newDay));
 
        }
    }

   public void doTimer(long start,long end){
 
	   t_start =start; 
	   t_end =end; 
	   ss=(end-start)/(1000);
	   if (accetimer != null) {
		   accetimer.cancel();
		   accetimer = new Timer();
		} else {
			accetimer = new Timer();
		}
	 //   AccessTabPanel.acceTimeFlag=true;
		long frequency = 1000;
		accetimer.schedule(new TimerTask() {
			@Override
			public void run() {
				
					try {
						showTime();
					} catch (Exception ex) {
						
						ex.printStackTrace();
					}
				
			}

		}, frequency, frequency);
		
	   
   } 
   
  public void showTime(){
	   //共计秒数 
	  int MM = (int)ss/60; //共计分钟数 
	  int hh=(int)ss/3600; //共计小时数 
	  int dd=(int)hh/24; //共计天数
	  
      int s_dd = (int) (ss/(60*60*24));//天
      int s_hh = (int) ((ss- s_dd*(60*60*24)))/3600;
      int s_mm = (int) ((ss- (s_dd*(60*60*24)+ s_hh*3600))/60);
      int s_ss = (int) (ss - (s_dd*(60*60*24)+ s_hh*3600 +s_mm*60));
      
      String timeLabel = "距离程序开始运行时间: "+s_dd+" 天"+s_hh+" 小时 "+s_mm+" 分钟"+s_ss+" 秒 ";
    //  AccessTabPanel.timeAccLabel.setText(timeLabel);
      
      ss--;
      if(ss<0){
    	  
    	  accetimer.cancel();
    //	  AccessTabPanel.startProceeAcceEtl();
    	   
    	  
      }
 }   
  
  /**
	 * 获取一个月的最后一天
	 * 
	 * @param dat
	 * @return
	 */
  public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
		String str = dat.substring(0, 8);
		String month = dat.substring(5, 7);
		int mon = Integer.parseInt(month);
		if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8
				|| mon == 10 || mon == 12) {
			str += "31";
		} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
			str += "30";
		} else {
			if (isLeapYear(dat)) {
				str += "29";
			} else {
				str += "28";
			}
		}
		return str;
	}
	
	/**
	 * 判断是否润年
	 * 
	 * @param ddate
	 * @return
	 */
	public static boolean isLeapYear(String ddate) {

		/**
		 * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
		 * 3.能被4整除同时能被100整除则不是闰年
		 */
		Date d = strToDate(ddate);
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(d);
		int year = gc.get(Calendar.YEAR);
		if ((year % 400) == 0)
			return true;
		else if ((year % 4) == 0) {
			if ((year % 100) == 0)
				return false;
			else
				return true;
		} else
			return false;
	}
	/**
	 * 将短时间格式字符串转换为时间 yyyy-MM-dd
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDate(String strDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}  
    
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值