甜咖啡

          我的IT空間

          javaSwing日期控件精確到年月日時分秒

          package dateapp;

          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.Component;
          import java.awt.Cursor;
          import java.awt.Frame;

          import java.awt.event.ActionEvent;
          import java.awt.event.ActionListener;
          import java.awt.event.MouseListener;
          import java.awt.event.MouseAdapter;
          import java.awt.event.MouseEvent;
          //import javax.swing.JFrame;
          import javax.swing.JButton;
          import javax.swing.JComboBox;
          import javax.swing.JDialog;
          import javax.swing.JPanel;
          import javax.swing.JLabel;
          import javax.swing.JSpinner;
          import javax.swing.JSpinner.NumberEditor;
          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;

          public class DateChooseJButton extends JButton {

           private DateChooser dateChooser = null;

           private String preLabel = "";

           public DateChooseJButton() {
            this(getNowDate());
           }

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

           public DateChooseJButton(Date date) {
            this("", date);
           }

           public DateChooseJButton(String preLabel, Date date) {
            if (preLabel != null)
             this.preLabel = preLabel;
            setDate(date);
            setBorder(null);
            setCursor(new Cursor(Cursor.HAND_CURSOR));
            super.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 HH:mm:ss");
           }

           // 覆蓋父類的方法
           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 = getText().substring(preLabel.length());
            try {
             return getDefaultDateFormat().parse(dateString);
            } catch (ParseException e) {
             return getNowDate();
            }

           }

           // 覆蓋父類的方法使之無效
           public void addActionListener(ActionListener listener) {
           }

           private class DateChooser extends JPanel implements ActionListener,
             ChangeListener {
            int startYear = 1980; // 默認【最小】顯示年份
            int lastYear = 2050; // 默認【最大】顯示年份
            int width = 400; // 界面寬度
            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;
            JComboBox minSpin;
            JComboBox secondBox;
            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);
             int currentMin = c.get(Calendar.MINUTE);
             int currentSecond = c.get(Calendar.SECOND);

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

             minSpin = new JComboBox();
             ;
             addComboBoxItem(minSpin);
             minSpin.setPreferredSize(new Dimension(45, 20));
             minSpin.setName("Min");
             minSpin.addItemListener(new java.awt.event.ItemListener() {
              public void itemStateChanged(java.awt.event.ItemEvent e) {
               JComboBox source = (JComboBox) e.getSource();
               Calendar c = getCalendar();
               if (source.getName().equals("Min")) {
                c.set(Calendar.MINUTE, getSelectedMin());
                setDate(c.getTime());
                return;
               }
              }
             });
             result.add(minSpin);

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

             secondBox = new JComboBox();
             addComboBoxItem(secondBox);
             secondBox.setPreferredSize(new Dimension(45, 20));
             secondBox.setName("Second");
             // secondBox.addActionListener(this) ;
             secondBox.addItemListener(new java.awt.event.ItemListener() {
              public void itemStateChanged(java.awt.event.ItemEvent e) {
               JComboBox source = (JComboBox) e.getSource();
               Calendar c = getCalendar();
               if (source.getName().equals("Second")) {
                c.set(Calendar.SECOND, getSelectedSecond());
                setDate(c.getTime());
                return;
               }
              }
             });

             result.add(secondBox);

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

             return result;
            }

            private void addComboBoxItem(JComboBox comboBox) {
             for (int i = 0; i < 60; i++) {
              comboBox.addItem(i);
             }

            }

            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(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(DateChooseJButton.this);
             if (dialog == null || dialog.getOwner() != owner)
              dialog = createDialog(owner);
             dialog.setLocation(getAppropriateLocation(owner, position));
             flushWeekAndDay();
             dialog.show();
            }

            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 getSelectedHour() {
             return ((Integer) hourSpin.getValue()).intValue();
            }

            private int getSelectedMin() {
             return (Integer) this.minSpin.getSelectedItem();
            }

            private int getSelectedSecond() {
             return (Integer) this.secondBox.getSelectedItem();
            }

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

           }

           public static void main(String[] args){
            new JButton();
           }
          }

          上述日期控件繼承JButton,使用時只要構造出來JButton對象就行了。


          posted on 2011-11-04 12:32 甜咖啡 閱讀(4456) 評論(1)  編輯  收藏

          評論

          # re: javaSwing日期控件精確到年月日時分秒 2012-02-22 14:48 vip87610600

          代碼太多了 啊  回復  更多評論   


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          <2011年11月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          統計

          常用鏈接

          留言簿(1)

          我參與的團隊

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 南投市| 安岳县| 台中市| 南江县| 贵州省| 辰溪县| 墨竹工卡县| 长岭县| 蕉岭县| 健康| 莲花县| 方城县| 沙雅县| 靖安县| 建德市| 芦溪县| 万山特区| 五家渠市| 盐池县| 福海县| 大埔县| 年辖:市辖区| 秦皇岛市| 喜德县| 安义县| 兴化市| 图木舒克市| 廊坊市| 寿光市| 丹凤县| 新乡市| 于都县| 筠连县| 铁岭市| 道孚县| 阿坝| 陵川县| 闽侯县| 临朐县| 灵宝市| 黄平县|