精华内容
下载资源
问答
  • java日期选择框

    千次阅读 2008-02-25 16:50:00
    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 j

    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.JDialog;
    import javax.swing.JFrame;
    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 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));
            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"); //按钮显示的日期格式 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 = 260; //界面宽度
            int height = 240; //界面高度
            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 daySpin;
            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 currentDay = c.get(Calendar.DAY_OF_MONTH);
                JPanel result = new JPanel();
                result.setLayout(new FlowLayout());
                result.setBackground(controlLineColor);
                yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                        startYear, lastYear, 1));
                yearSpin.setPreferredSize(new Dimension(60, 25));
                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(50, 25));
                monthSpin.setName("Month");
                monthSpin.addChangeListener(this);
                result.add(monthSpin);
                JLabel monthLabel = new JLabel("月");
                monthLabel.setForeground(controlTextColor);
                result.add(monthLabel);
                daySpin = new JSpinner(new SpinnerNumberModel(currentDay, 1, 31,
                        1));
                daySpin.setPreferredSize(new Dimension(50, 25));
                daySpin.setName("Day");
                daySpin.addChangeListener(this);
                result.add(daySpin);
                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.CENTER);
                    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.CENTER);
                        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(DateChooserJButton.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 getSelectedDay() {
                return ((Integer) daySpin.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("Day")) {
                    c.set(Calendar.DAY_OF_MONTH, getSelectedDay());
                    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);
                daySpin.setValue(Integer.parseInt(source.getText()));
                setDate(c.getTime());
            }
        }//end class DateChooser
    
        public static void main(String args[]) {
            DateChooserJButton d = new DateChooserJButton();
        }
    }

    //例子2
    
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package comparedistro;
    
    /**
     *
     * @author luolai
     */
    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.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    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;
    
    /**
     *
     * YouAreStupid 收集网上靠谱的例子,修改后的Swing日期 时间选择器,因为修改时间匆忙,希望有时间的朋友继续改进。 例子原作者:zjw
     * 修改/完善:YouAreStupid
     */
    public class NewDateChooserJButton extends JButton {
    
        private DateChooser dateChooser = null;
        private String preLabel = "";
        private String originalText = null;
        private SimpleDateFormat sdf = null;
    
        public NewDateChooserJButton() {
            this(getNowDate());
        }
    
        public NewDateChooserJButton(String dateString) {
            this();
            setText(getDefaultDateFormat(), dateString);
            //保存原始是日期时间   
            initOriginalText(dateString);
        }
    
        public NewDateChooserJButton(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 NewDateChooserJButton(Date date) {
            this("", date);
            //记忆原始日期时间   
            initOriginalText(date);
        }
    
        public NewDateChooserJButton(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();
                    }
                    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) {
            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 = 480; // 界面宽度   
            int height = 320; // 界面高度   
            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按钮文字色   
            /**
             * 点击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 currentHour = c.get(Calendar.HOUR_OF_DAY);
                int currentMinute = 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(60, 25));
                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(45, 25));
                monthSpin.setName("Month");
                monthSpin.addChangeListener(this);
                result.add(monthSpin);
    
                JLabel monthLabel = new JLabel("月");
                monthLabel.setForeground(controlTextColor);
                result.add(monthLabel);
    
                //如果这里要能够选择,会要判断很多东西,比如每个月分别由多少日,以及闰年问题.所以,就干脆把Enable设为false   
                daySpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1, 31, 1));
                daySpin.setPreferredSize(new Dimension(45, 25));
                daySpin.setName("Day");
                daySpin.addChangeListener(this);
                daySpin.setEnabled(false);
                daySpin.setToolTipText("请下下面的日历面板中进行选择哪一天!");
                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(45, 25));
                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(45, 25));
                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(45, 25));
                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.CENTER);
                    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.CENTER);
                        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() {
                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());
                        //隐藏日历对话框   
                        dialog.setVisible(false);
                    }
                });
                //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.setUndecorated(true);//隐藏关闭按钮
                result.pack();
                result.setSize(width, height);
                return result;
            }
    
            void showDateChooser(Point position) {
                Frame owner = (Frame) SwingUtilities.getWindowAncestor(NewDateChooserJButton.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 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);
                    daysButton[i][j].setFont(new java.awt.Font("宋体", 1, 28));//当前选中字体为粗体
                } else {
                    daysButton[i][j].setForeground(todayBackColor);
                    daysButton[i][j].setFont(new java.awt.Font("宋体", 1, 28));//当前选中字体为粗体
                }
            }
    
            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);
                        daysButton[i][j].setFont(new java.awt.Font("宋体", 0, 18));
                        dayNo++;
                    }
                }
                dayColorUpdate(false);
            }
    
            /**
             * 选择日期时的响应事件
             */
            @Override
            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;
                }
                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;
                }
    
                dayColorUpdate(true);
    
                if (source.getName().equals("Year")) {
                    c.set(Calendar.YEAR, getSelectedYear());
                } else if (source.getName().equals("Month")) {
                    c.set(Calendar.MONTH, getSelectedMonth() - 1);
                }
                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));
                dialog.setVisible(false);
            }
        }
    
        /**
         * 测试方法
         */
        public static void main(String[] args) {
            JFrame mainFrame = new JFrame("测试");
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainFrame.setSize(480, 480);
            mainFrame.setLayout(new java.awt.BorderLayout());
            mainFrame.add(new NewDateChooserJButton(), java.awt.BorderLayout.CENTER);
    
            Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screenSize = kit.getScreenSize();
            int width = (int) screenSize.getWidth();
            int height = (int) screenSize.getHeight();
            int w = mainFrame.getWidth();
            int h = mainFrame.getHeight();
            mainFrame.setLocation((width - w) / 2, (height - h) / 2);
    
            mainFrame.setVisible(true);
        }
    }
    
    


    展开全文
  • /**DateChooser.java**Createdon2007年8月20日,下午6:07**Tochangethistemplate,chooseTools|TemplateManager*andopenthetemplateintheeditor.*/importjava.awt.BasicStroke;importjava.awt.BorderL...

    /** DateChooser.java

    *

    * Created on 2007年8月20日, 下午6:07

    *

    * To change this template, choose Tools | Template Manager

    * and open the template in the editor.*/importjava.awt.BasicStroke;importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.Component;importjava.awt.Cursor;importjava.awt.Dimension;importjava.awt.Font;importjava.awt.Graphics;importjava.awt.Graphics2D;importjava.awt.GridLayout;importjava.awt.Point;importjava.awt.Polygon;importjava.awt.Stroke;importjava.awt.Toolkit;importjava.awt.event.FocusEvent;importjava.awt.event.FocusListener;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjava.awt.event.MouseMotionListener;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Calendar;importjava.util.Comparator;importjava.util.Date;importjava.util.List;importjavax.swing.BorderFactory;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.Popup;importjavax.swing.PopupFactory;importjavax.swing.SwingUtilities;importjavax.swing.event.AncestorEvent;importjavax.swing.event.AncestorListener;/***

    *@authorhadeslee*/publicclassDateChooserextendsJPanel{privateDate initDate;privateCalendar now=Calendar.getInstance();privateCalendar select;privateJPanel monthPanel;//月历privateJP1 jp1;//四块面板,组成privateJP2 jp2;privateJP3 jp3;privateJP4 jp4;privateFont font=newFont("宋体",Font.PLAIN,12);privatefinalLabelManager lm=newLabelManager();privateJLabel showDate;//,toSelect;privateSimpleDateFormat sdf=newSimpleDateFormat("yyyy年MM月dd日");privatebooleanisShow=false;privatePopup pop;/*** Creates a new instance of DateChooser*/publicDateChooser() {this(newDate());

    }publicDateChooser(Date date){

    initDate=date;

    select=Calendar.getInstance();

    select.setTime(initDate);

    initPanel();

    initLabel();

    }publicvoidsetEnabled(booleanb){super.setEnabled(b);

    showDate.setEnabled(b);

    }/***得到当前选择框的日期*/publicDate getDate(){returnselect.getTime();

    }//根据初始化的日期,初始化面板privatevoidinitPanel(){

    monthPanel=newJPanel(newBorderLayout());

    monthPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));

    JPanel up=newJPanel(newBorderLayout());

    up.add(jp1=newJP1(),BorderLayout.NORTH);

    up.add(jp2=newJP2(),BorderLayout.CENTER);

    monthPanel.add(jp3=newJP3(),BorderLayout.CENTER);

    monthPanel.add(up,BorderLayout.NORTH);

    monthPanel.add(jp4=newJP4(),BorderLayout.SOUTH);this.addAncestorListener(newAncestorListener(){publicvoidancestorAdded(AncestorEvent event) {

    }publicvoidancestorRemoved(AncestorEvent event) {

    }//只要祖先组件一移动,马上就让popup消失publicvoidancestorMoved(AncestorEvent event) {

    hidePanel();

    }

    });

    }//初始化标签privatevoidinitLabel(){

    showDate=newJLabel(sdf.format(initDate));

    showDate.setRequestFocusEnabled(true);

    showDate.addMouseListener(newMouseAdapter(){publicvoidmousePressed(MouseEvent me){

    showDate.requestFocusInWindow();

    }

    });//toSelect=new JLabel(sdf.format(initDate));//toSelect.setBorder(BorderFactory.createLineBorder(Color.BLACK));//toSelect.setRequestFocusEnabled(true);this.setBackground(Color.WHITE);this.add(showDate,BorderLayout.CENTER);//this.add(toSelect,BorderLayout.EAST);this.setPreferredSize(newDimension(90,25));this.setBorder(BorderFactory.createLineBorder(Color.GRAY));

    showDate.addMouseListener(newMouseAdapter(){publicvoidmouseEntered(MouseEvent me){if(showDate.isEnabled()){

    showDate.setCursor(newCursor(Cursor.HAND_CURSOR));

    showDate.setForeground(Color.RED);

    }

    }publicvoidmouseExited(MouseEvent me){if(showDate.isEnabled()){

    showDate.setCursor(newCursor(Cursor.DEFAULT_CURSOR));

    showDate.setForeground(Color.BLACK);

    }

    }publicvoidmousePressed(MouseEvent me){if(showDate.isEnabled()){

    showDate.setForeground(Color.CYAN);if(isShow){

    hidePanel();

    }else{

    showPanel(showDate);

    }

    }

    }publicvoidmouseReleased(MouseEvent me){if(showDate.isEnabled()){

    showDate.setForeground(Color.BLACK);

    }

    }

    });

    showDate.addFocusListener(newFocusListener(){publicvoidfocusLost(FocusEvent e){

    hidePanel();

    }publicvoidfocusGained(FocusEvent e){

    }

    });

    }//根据新的日期刷新privatevoidrefresh(){

    jp1.updateDate();

    jp3.updateDate();

    SwingUtilities.updateComponentTreeUI(this);

    }//提交日期privatevoidcommit(){

    System.out.println("选中的日期是:"+sdf.format(select.getTime()));

    showDate.setText(sdf.format(select.getTime()));

    hidePanel();

    }privatevoidhidePanel(){if(pop!=null){

    isShow=false;

    pop.hide();

    pop=null;

    }

    }privatevoidshowPanel(Component owner){if(pop!=null){

    pop.hide();

    }

    Point show=newPoint(0,showDate.getHeight());

    SwingUtilities.convertPointToScreen(show,showDate);

    Dimension size=Toolkit.getDefaultToolkit().getScreenSize();intx=show.x;inty=show.y;if(x<0){

    x=0;

    }if(x>size.width-295){

    x=size.width-295;

    }if(y

    }else{

    y-=188;

    }

    pop=PopupFactory.getSharedInstance().getPopup(owner,monthPanel,x,y);

    pop.show();

    isShow=true;

    }privateclassJP1extendsJPanel{

    JLabel left,right,center;publicJP1(){super(newBorderLayout());this.setBackground(newColor(160,185,215));

    initJP1();

    }privatevoidinitJP1(){

    left=newJLabel("<

    left.setToolTipText("上一月");

    right=newJLabel(">>",JLabel.CENTER);

    right.setToolTipText("下一月");

    left.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));

    right.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));

    center=newJLabel("",JLabel.CENTER);

    updateDate();this.add(left,BorderLayout.WEST);this.add(center,BorderLayout.CENTER);this.add(right,BorderLayout.EAST);this.setPreferredSize(newDimension(295,25));

    left.addMouseListener(newMouseAdapter(){publicvoidmouseEntered(MouseEvent me){

    left.setCursor(newCursor(Cursor.HAND_CURSOR));

    left.setForeground(Color.RED);

    }publicvoidmouseExited(MouseEvent me){

    left.setCursor(newCursor(Cursor.DEFAULT_CURSOR));

    left.setForeground(Color.BLACK);

    }publicvoidmousePressed(MouseEvent me){

    select.add(Calendar.MONTH,-1);

    left.setForeground(Color.WHITE);

    refresh();

    }publicvoidmouseReleased(MouseEvent me){

    left.setForeground(Color.BLACK);

    }

    });

    right.addMouseListener(newMouseAdapter(){publicvoidmouseEntered(MouseEvent me){

    right.setCursor(newCursor(Cursor.HAND_CURSOR));

    right.setForeground(Color.RED);

    }publicvoidmouseExited(MouseEvent me){

    right.setCursor(newCursor(Cursor.DEFAULT_CURSOR));

    right.setForeground(Color.BLACK);

    }publicvoidmousePressed(MouseEvent me){

    select.add(Calendar.MONTH,1);

    right.setForeground(Color.WHITE);

    refresh();

    }publicvoidmouseReleased(MouseEvent me){

    right.setForeground(Color.BLACK);

    }

    });

    }privatevoidupdateDate(){

    center.setText(select.get(Calendar.YEAR)+"年"+(select.get(Calendar.MONTH)+1)+"月");

    }

    }privateclassJP2extendsJPanel{publicJP2(){this.setPreferredSize(newDimension(295,20));

    }protectedvoidpaintComponent(Graphics g){

    g.setFont(font);

    g.drawString("星期日 星期一 星期二 星期三 星期四 星期五 星期六",5,10);

    g.drawLine(0,15,getWidth(),15);

    }

    }privateclassJP3extendsJPanel{publicJP3(){super(newGridLayout(6,7));this.setPreferredSize(newDimension(295,100));

    initJP3();

    }privatevoidinitJP3(){

    updateDate();

    }publicvoidupdateDate(){this.removeAll();

    lm.clear();

    Date temp=select.getTime();

    Calendar select=Calendar.getInstance();

    select.setTime(temp);

    select.set(Calendar.DAY_OF_MONTH,1);intindex=select.get(Calendar.DAY_OF_WEEK);intsum=(index==1?8:index);

    select.add(Calendar.DAY_OF_MONTH,0-sum);for(inti=0;i<42;i++){

    select.add(Calendar.DAY_OF_MONTH,1);

    lm.addLabel(newMyLabel(select.get(Calendar.YEAR),

    select.get(Calendar.MONTH),select.get(Calendar.DAY_OF_MONTH)));

    }for(MyLabel my:lm.getLabels()){this.add(my);

    }

    select.setTime(temp);

    }

    }privateclassMyLabelextendsJLabelimplementsComparator,

    MouseListener,MouseMotionListener{privateintyear,month,day;privatebooleanisSelected;publicMyLabel(intyear,intmonth,intday){super(""+day,JLabel.CENTER);this.year=year;this.day=day;this.month=month;this.addMouseListener(this);this.addMouseMotionListener(this);this.setFont(font);if(month==select.get(Calendar.MONTH)){this.setForeground(Color.BLACK);

    }else{this.setForeground(Color.LIGHT_GRAY);

    }if(day==select.get(Calendar.DAY_OF_MONTH)){this.setBackground(newColor(160,185,215));

    }else{this.setBackground(Color.WHITE);

    }

    }publicbooleangetIsSelected(){returnisSelected;

    }publicvoidsetSelected(booleanb,booleanisDrag){

    isSelected=b;if(b&&!isDrag){inttemp=select.get(Calendar.MONTH);

    select.set(year,month,day);if(temp==month){

    SwingUtilities.updateComponentTreeUI(jp3);

    }else{

    refresh();

    }

    }this.repaint();

    }protectedvoidpaintComponent(Graphics g){if(day==select.get(Calendar.DAY_OF_MONTH)&&month==select.get(Calendar.MONTH)){//如果当前日期是选择日期,则高亮显示g.setColor(newColor(160,185,215));

    g.fillRect(0,0,getWidth(),getHeight());

    }if(year==now.get(Calendar.YEAR)&&month==now.get(Calendar.MONTH)&&day==now.get(Calendar.DAY_OF_MONTH)){//如果日期和当前日期一样,则用红框Graphics2D gd=(Graphics2D)g;

    gd.setColor(Color.RED);

    Polygon p=newPolygon();

    p.addPoint(0,0);

    p.addPoint(getWidth()-1,0);

    p.addPoint(getWidth()-1,getHeight()-1);

    p.addPoint(0,getHeight()-1);

    gd.drawPolygon(p);

    }if(isSelected){//如果被选中了就画出一个虚线框出来Stroke s=newBasicStroke(1.0f,BasicStroke.CAP_SQUARE,

    BasicStroke.JOIN_BEVEL,1.0f,newfloat[]{2.0f,2.0f},1.0f);

    Graphics2D gd=(Graphics2D)g;

    gd.setStroke(s);

    gd.setColor(Color.BLACK);

    Polygon p=newPolygon();

    p.addPoint(0,0);

    p.addPoint(getWidth()-1,0);

    p.addPoint(getWidth()-1,getHeight()-1);

    p.addPoint(0,getHeight()-1);

    gd.drawPolygon(p);

    }super.paintComponent(g);

    }publicbooleancontains(Point p){returnthis.getBounds().contains(p);

    }privatevoidupdate(){

    repaint();

    }publicvoidmouseClicked(MouseEvent e) {

    }publicvoidmousePressed(MouseEvent e) {

    isSelected=true;

    update();

    }publicvoidmouseReleased(MouseEvent e) {

    Point p=SwingUtilities.convertPoint(this,e.getPoint(),jp3);

    lm.setSelect(p,false);

    commit();

    }publicvoidmouseEntered(MouseEvent e) {

    }publicvoidmouseExited(MouseEvent e) {

    }publicvoidmouseDragged(MouseEvent e) {

    Point p=SwingUtilities.convertPoint(this,e.getPoint(),jp3);

    lm.setSelect(p,true);

    }publicvoidmouseMoved(MouseEvent e) {

    }publicintcompare(MyLabel o1, MyLabel o2) {

    Calendar c1=Calendar.getInstance();

    c1.set(o1.year,o2.month,o1.day);

    Calendar c2=Calendar.getInstance();

    c2.set(o2.year,o2.month,o2.day);returnc1.compareTo(c2);

    }

    }privateclassLabelManager{privateListlist;publicLabelManager(){

    list=newArrayList();

    }publicListgetLabels(){returnlist;

    }publicvoidaddLabel(MyLabel my){

    list.add(my);

    }publicvoidclear(){

    list.clear();

    }publicvoidsetSelect(MyLabel my,booleanb){for(MyLabel m:list){if(m.equals(my)){

    m.setSelected(true,b);

    }else{

    m.setSelected(false,b);

    }

    }

    }publicvoidsetSelect(Point p,booleanb){//如果是拖动,则要优化一下,以提高效率if(b){//表示是否能返回,不用比较完所有的标签,能返回的标志就是把上一个标签和//将要显示的标签找到了就可以了booleanfindPrevious=false,findNext=false;for(MyLabel m:list){if(m.contains(p)){

    findNext=true;if(m.getIsSelected()){

    findPrevious=true;

    }else{

    m.setSelected(true,b);

    }

    }elseif(m.getIsSelected()){

    findPrevious=true;

    m.setSelected(false,b);

    }if(findPrevious&&findNext){return;

    }

    }

    }else{

    MyLabel temp=null;for(MyLabel m:list){if(m.contains(p)){

    temp=m;

    }elseif(m.getIsSelected()){

    m.setSelected(false,b);

    }

    }if(temp!=null){

    temp.setSelected(true,b);

    }

    }

    }

    }privateclassJP4extendsJPanel{publicJP4(){super(newBorderLayout());this.setPreferredSize(newDimension(295,20));this.setBackground(newColor(160,185,215));

    SimpleDateFormat sdf=newSimpleDateFormat("yyyy年MM月dd日");finalJLabel jl=newJLabel("今天:"+sdf.format(newDate()));

    jl.setToolTipText("点击回到今天日期");this.add(jl,BorderLayout.CENTER);

    jl.addMouseListener(newMouseAdapter(){publicvoidmouseEntered(MouseEvent me){

    jl.setCursor(newCursor(Cursor.HAND_CURSOR));

    jl.setForeground(Color.RED);

    }publicvoidmouseExited(MouseEvent me){

    jl.setCursor(newCursor(Cursor.DEFAULT_CURSOR));

    jl.setForeground(Color.BLACK);

    }publicvoidmousePressed(MouseEvent me){

    jl.setForeground(Color.WHITE);

    select.setTime(newDate());

    refresh();

    commit();

    }publicvoidmouseReleased(MouseEvent me){

    jl.setForeground(Color.BLACK);

    }

    });

    }

    }publicstaticvoidmain(String[] args) {finalDateChooser mp=newDateChooser();

    JFrame jf=newJFrame("test");

    jf.add(mp,BorderLayout.CENTER);

    jf.add(newJButton("测试用的"),BorderLayout.NORTH);

    jf.pack();

    jf.setLocationRelativeTo(null);

    jf.setVisible(true);

    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    }

    展开全文
  • ·我用java写了个星期查询代码,有的日期对有的日期错,求帮忙看看哪里有问题!!import java.util.*;public class Test1 {public static void main(String[] args){int chun=1900,chum=1,zong=0;int run=0,ping=0;...

    ·

    我用java写了个星期查询代码,有的日期对有的日期错,求帮忙看看哪里有问题!!

    import java.util.*;

    public class Test1 {

    public static void main(String[] args){

    int chun=1900,chum=1,zong=0;

    int run=0,ping=0;

    Scanner in=new Scanner(System.in);

    System.out.println("某年月日星期几查询(星期日为0)");

    System.out.print("输入你要查询的年份:");

    int n=in.nextInt();

    System.out.print("输入你要查询的月份:");

    int m=in.nextInt();

    System.out.print("输入你要查询的日份:");

    int ri=in.nextInt();

    while(chun

    if(chun%4==0&&chun%100!=0||chun%400==0){

    run+=366;

    }

    else{

    ping+=365;

    }

    chun++;

    }

    zong=run+ping;

    while(chum

    if(chum==2){

    zong+=28;

    }

    else if(chum==4||chum==6||chum==9||chum==11){

    zong+=30;

    }

    else{

    zong+=31;

    }

    chum++;

    }

    zong+=ri;

    System.out.print(n+"年"+m+"月"+ri+"日"+"为星期"+zong%7);

    }

    }

    解答:

    就给你一个简单一点的吧,java有自带的Calendar类来处理日期和时间的,你非得折腾一下。

    intyear,month,day;//获取年、月、日的就不写了//初始化日期

    Calendar c=Calendar.getInstance();//设置日期,注意月份是从0开始的

    c.set(year,month-1,day);//星期天为1,星期一为2,其余类推

    int d=c.get(Calendar.DAY_OF_WEEK)-1;

    System.out.println(d);

    ·····

    ·

    展开全文
  • java 日期选择框源码

    2014-08-10 14:11:23
    构建日期选择页面,实现了日期选择功能,可运行
  • 引入js*时间:$('.form_datetime').datetimepicker({/* minView: "month", *///选择日期后,不会再跳转去选择时分秒language: 'zh-CN',dateFormat: 'yyyy-mm-dd',//日期显示格式timeFormat:'HH:mm:ss',//时间显示格式...

    引入js

    *时间:

    $('.form_datetime').datetimepicker({

    /* minView: "month", *///选择日期后,不会再跳转去选择时分秒

    language: 'zh-CN',

    dateFormat: 'yyyy-mm-dd',//日期显示格式

    timeFormat:'HH:mm:ss',//时间显示格式

    todayBtn: 1,

    autoclose: 1,

    minView:0, //0表示可以选择小时、分钟 1只可以选择小时

    minuteStep:1,//分钟间隔1分钟

    });

    format

    String. 默认值: 'mm/dd/yyyy'

    日期格式, p, P, h, hh, i, ii, s, ss, d, dd, m, mm, M, MM, yy, yyyy 的任意组合。

    这个是扯淡的,就是个意思,你可以自己设计样式,但是里面的字母都代表不同属性:

    符号

    意义

    p

    12小时制且小写(‘am’ or ‘pm’)

    P

    12小时制且大写(‘AM’ or ‘PM’)

    s

    秒,前面不补0

    ss

    秒,前面补0

    i

    分,前面不补0

    ii

    分,前面补0

    h

    时,24小时制,前面不补0

    hh

    时,24小时制,前面补0

    H

    时,12小时制,前面不补0

    HH

    时,12小时制,前面补0

    d

    日,前面不补0

    dd

    日,前面补0

    m

    月,数字表示,前面不补0 如:4

    mm

    月,数字表示,前面补0 如:04

    M

    月,缩写表示,前面补0 如:Apr

    MM

    月,全称表示,前面补0 如:April

    yy

    年,后两位 如:16

    yyyy

    年,全部 如:2016

    minView — 最精确的时间

    Number, String类型

    默认值:0, ‘hour’

    日期时间选择器所能够提供的最精确的时间选择视图。

    可接受的值:

    意义

    0

    从小时视图开始,选分

    1

    从天视图开始,选小时

    2

    从月视图开始,选天

    3

    从年视图开始,选月

    4

    从十年视图开始,选年

    startDate — 开始时间

    Date类型

    默认值:开始时间

    之前的日期都不能选择,这个时间之后的时间才能选择。

    咱们做一个常用的Demo,就是只能选现在之后的时间:

    例如:

    var date = new Date();

    $("#demo").datetimepicker({

    startDate: date

    });

    endDate— 结束时间

    Date类型

    默认值:结束时间

    这个时间后面的不能再选择。

    用法同上,不再赘述。

    daysOfWeekDisabled — 一周的周几不能选

    String, Array类型

    默认值:”, []

    0(星期日)到6(星期六)

    可以有多个。

    例如:

    $("#demo").datetimepicker({

    daysOfWeekDisabled: [0,4,6]

    });

    autoclose — 选完时间后是否自动关闭

    Boolean类型

    默认值:false

    当选择一个日期之后是否立即关闭此日期时间选择器。

    minView — 最精确的时间

    Number, String类型

    默认值:0, ‘hour’

    日期时间选择器所能够提供的最精确的时间选择视图。

    可接受的值:

    意义

    0

    从小时视图开始,选分

    1

    从天视图开始,选小时

    2

    从月视图开始,选天

    3

    从年视图开始,选月

    4

    从十年视图开始,选年

    例如:

    $("#demo").datetimepicker({

    minView : 2

    });

    maxView — 最高能展示的时间

    Number, String类型

    默认值:4, ‘decade’

    日期时间选择器最高能展示的选择范围视图。

    todayBtn — 当天日期按钮

    Boolean, “linked”类型

    默认值:false’

    如果此值为true 或 “linked”,则在日期时间选择器组件的底部显示一个 “Today” 按钮用以选择当前日期。如果是true的话,”Today” 按钮仅仅将视图转到当天的日期,如果是”linked”,当天日期将会被选中。

    例如:

    $("#demo").datetimepicker({

    todayBtn : true

    });

    initialDate — 初始化日期时间

    todayHighlight — 当天日期高亮

    Boolean类型

    默认值:false

    如果为true, 高亮当前日期。

    不再举例。

    keyboardNavigation — 方向键改变日期

    Boolean类型

    默认值:false

    是否允许通过方向键改变日期。

    不再举例。

    language— 语言

    String类型

    默认值:’en’

    中文:’zh-CN’ (设置中文的时候要引用到中文的js)

    forceParse— 强制解析

    Boolean类型

    默认值:true

    就是你输入的可能不正规,但是它胡强制尽量解析成你规定的格式(format)

    minuteStep — 步进值

    Number类型

    默认值:5

    此数值被当做步进值用于构建小时视图。就是最小的视图是每5分钟可选一次。是以分钟为单位的。

    pickerPosition — 选择框位置

    String类型

    默认值:’bottom-right’

    还支持 : ‘bottom-left’,’top-right’,’top-left’

    可以试试看,他拿出位置会发生变化。

    showMeridian — 是否显示上下午

    Boolean类型

    默认值:false

    展开全文
  • java 日期选择框 应用例子

    千次阅读 2011-10-13 19:38:33
    /*  * DateChooser.java  *  * Created on 2007年8月22日, 下午6:07  *  * To change this template, choose Tools | Template Manager  * and open
  • java GUI 性别单选框 日期选择框

    千次阅读 2019-06-03 13:48:42
    /* 性别单选 */ sex = new JLabel("性 别"); sex.setBounds(20, 105, 105, 30); man = new JRadioButton("男"); man.setSelected(true); woman = new JRadioButton("女"); man.setBou...
  • varDS_x,DS_y;functiondateSelector()//构造...functiondateSelector()//构造dateSelector对象,用来实现一个日历形式的日期输入框。{varmyDate=newDate();this.year=myDate.getFullYear();//定义year属...
  • JSP、Java实现选择框多级连动环境:DB2 9.1J2SDK 1.5Servlet 2.4一、问题在web开发中,经常会遇到两级三级甚至更多级的选项框连动的情况,一般情况下都考虑用js来实现,但是在有大量等级选项的情况下,js实现也很...
  • 摘 要 本文针对Java语言的特点,提出了在程序中动态添加和删除列表中的列表元素并在结束操作时获取列表元素的实现方法,并给出了具体开发的...如果有很多固定的选项供用户选择,列表是很好的解决方案。用户在...
  • 利用Android应用框架提供的DatePicker(日期选择器)和TimePicker(时间选择器),实现日期时间选择器。Dialog的Content布局文件(date_time_dialog.xml):android:layout_width="fill_parent"android:layout_height=...
  • Java+Selenium框架,对日期选择器取决在日期选择控件,但只要元素在dom里面就能找到方法定位该元素。 @Test public void test1() throws Exception { driver.get(baseUrl); // 查找入住文本框 WebElement ...
  • 我们可以用java获取当前日期,然后用Selenium结合JS代码就可以直接往文本框输入内容。 像这种选择时间的input标签都会有一个readonly=""标签,这个时候我们就只能选择时间,不能手动输入,解决办法如下: Date ...
  • Java日期选择器组件应用实例 源码,定义了界面组件,有父窗口(Farm),不带日期参数的 DateChooser,定义了月历表格配色和滚动条颜色,本Java日历选择器源码文件功能说明:  [DateChooser.java] Java 日期选择控件...
  • Java日期选择器,Pallet.backGroundColor = Color.gray; //底色  //月历表格配色----------------//  Pallet.palletTableColor = Color.white; //日历表底色  Pallet.todayBackColor = Color.pink; //今天背景...
  • 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;imp...
  • JSP、Java实现选择框多级连动   环境:DB2 9.1J2SDK 1.5Servlet 2.4     一、问题 在web开发中,经常会遇到两级三级甚至更多级的选项框连动的情况,一般情况下都考虑用js来实现,但是...
  • packagecom.example....importjava.lang.reflect.Field;importandroid.app.AlertDialog;importandroid.content.Context;importandroid.content.DialogInterface;importandroid.content.DialogInterfac...
  • java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] at java.sql.Timestamp.valueOf(Timestamp.java:204) at ...
  • 日期选择框代码

    千次阅读 2008-03-21 13:56:00
    /* * DateChooser.java * * Created on 2007年3月31日, 上午 10:49 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ import java.text....
  • DatePicker - 日期选择插件在一些WEB系统中,日期选择插件必不可少的功能,今天为大家分享几个不错的日期选择插件。希望对大家有所帮助。1)My97DatePicker是一个更全面,更人性化,并且速度一流的日期选择控件。具有...
  • 我把bootstrap和bootstrapdaetimepicker包还有jquery都导入到eclipse工程里了,代码也写好了,但是不知道为什么boostrap别的功能都能实现,就是运行时日期控件无法弹出日期选择框。这是我的代码,求大神帮忙看看! ...
  • Java常用日志框架及实现

    千次阅读 2015-12-16 09:32:53
    本文简单介绍了一下Java的日志框架,包括接口库和实现库,并在具体使用选择上给出了一些建议。 日志接口库 common-logging common-logging为众多具体的日志实现库提供了一个统一的接口。它允许在运行时绑定到...
  • 如何创建日期微调器,该日期将EditText中的当前日期显示为默认值,并在Spinner中显示将来的日期(例如接下来的30天)我在许多应用程序中使用了日期选择器,因此我熟悉日期选择器对话框,但对日期微调器一无所知。...
  • Swing日期时间选择框控件

    千次阅读 2012-03-07 15:24:39
    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; im
  • 本篇主要介绍跟后台数据绑定相关度不大的简单控件,直接写了一个...<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 449
精华内容 179
关键字:

java日期选择框

java 订阅