Swing 寫的日期時間組件

jopen 11年前發布 | 36K 次閱讀 Swing Java開發

在網上收集的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;
    }  

}

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!