Java制作的日期选择控件

来源:互联网 发布:完数c语言程序 编辑:程序博客网 时间:2024/05/17 08:48

 Java制作的日期选择控件,经测试没有问题,主要包括以下类:

主类:CDateComponent

           提供二个方法:

            getSelectedDateByString():以字符串的形式返回选择的日期

            getSelectedDate():以java.util.Date的形式返回选择的日期

内部类:DateComponent,日期选择窗口

               YearAndMonthPanel,选择年和月份面板

               WeekPanel,星期显示面板

               DayPanel,日选择面板

               Handler,处理鼠标点击事件,显示日期选择窗口

运行效果如下:

            

程序代码如下:          

import javax.swing.*;
import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.awt.event.*;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: cxwu
 * Date: 2007-12-13
 * Time: 21:50:20
 * To change this template use File | Settings | File Templates.
 
*/

public class CDateComponent extends JPanel{
    
private JTextField txtShow;
    
private boolean isShow = false//do the DataComponent display?
    private JComboBox cbxYear;
    
private JComboBox cbxMonth;
    
private DayPanel dp;
    
private DateComponent dc;//DateComponent view for user selecting date
    public CDateComponent(){
        txtShow 
= new JTextField(15);
        Icon icon 
= new ImageIcon("src/images/calendar.gif");
        JLabel lblIcon 
= new JLabel(icon);
        add(txtShow);
        add(lblIcon);
        lblIcon.addMouseListener(
new Handler());
        setBorder(BorderFactory.createRaisedBevelBorder());
    }

    
//get the user selected date by java.lang.String
    public String getSelectedDateByString(){
        
return txtShow.getText().trim();
    }

    
//get the user selected date by java.util.Date
    public Date getSelectedDate(){
        DateFormat df 
= DateFormat.getDateInstance();
        Date date 
= new Date();
        
try{
            date 
= df.parse(getSelectedDateByString());
        }
catch(Exception e){
            System.out.println(
"日期的格式不对!");
        }

        
return date;
    }

    
//handler mouse event on txtShow,to show the DateComponent view on screen
    class Handler extends MouseAdapter{
        
public void mousePressed(MouseEvent e) {
            
if(!isShow){
                isShow 
= true;
                Point pt 
= e.getPoint();
                SwingUtilities.convertPointToScreen(pt,(JLabel)e.getSource());
                Dimension screen 
= getToolkit().getScreenSize();
                dc 
= new DateComponent();
                
//decided the position of the DateComponent view
                int x = pt.x + 5;
                
int y = pt.y + 5;
                
int w = 360;
                
int h = 230;
                
if(screen.getWidth() < (x + w) && screen.getHeight() < (y + h)){
                    x 
= x - 360;
                    y 
= y - 230;
                }
else if(screen.getWidth() < (x + w)){
                    x 
= x - 360;
                }
else if(screen.getHeight() < (y + h)){
                    y 
= y - 230;
                }

                dc.setBounds(x,y,w,h);
                dc.setVisible(
true);
            }

        }

    }

    
//supply the Year and the Month list for the user selecting
    class YearAndMonthPanel extends JPanel{
        JButton btnLeftYear;
        JButton btnRightYear;
        JButton btnLeftMonth;
        JButton btnRightMonth;
        
public YearAndMonthPanel(){
            setLayout(
new FlowLayout(0,4,0));
            btnLeftYear 
= new JButton("<<");
            btnRightYear 
= new JButton(">>");
            btnLeftMonth 
= new JButton("<<");
            btnRightMonth 
= new JButton(">>");
            cbxYear 
= new JComboBox();
            cbxYear.setPreferredSize(
new Dimension(64,27));
            cbxMonth 
= new JComboBox();
            cbxMonth.setPreferredSize(
new Dimension(64,27));
            addYearAndMonth();
            add(btnLeftYear);
            add(cbxYear);
            add(btnRightYear);
            add(btnLeftMonth);
            add(cbxMonth);
            add(btnRightMonth);
            btnLeftYear.addActionListener(
new ActionListener() {
                
public void actionPerformed(ActionEvent e) {
                    
int index = cbxYear.getSelectedIndex();
                    
if(index == 0){
                        
return;
                    }

                    cbxYear.setSelectedIndex(index 
- 1);
                    updateDayShow();
                }

            }
);
            btnRightYear.addActionListener(
new ActionListener() {
                
public void actionPerformed(ActionEvent e) {
                    
int index = cbxYear.getSelectedIndex();
                    
if(index == cbxYear.getItemCount() - 1){
                        
return;
                    }

                    cbxYear.setSelectedIndex(index 
+ 1);
                    updateDayShow();
                }

            }
);
            btnLeftMonth.addActionListener(
new ActionListener() {
                
public void actionPerformed(ActionEvent e) {
                    
int index = cbxMonth.getSelectedIndex();
                    
if(index == 0){
                        
return;
                    }

                    cbxMonth.setSelectedIndex(index 
- 1);
                    updateDayShow();
                }

            }
);
            btnRightMonth.addActionListener(
new ActionListener() {
                
public void actionPerformed(ActionEvent e) {
                    
int index = cbxMonth.getSelectedIndex();
                    
if(index == 11){
                        
return;
                    }

                    cbxMonth.setSelectedIndex(index 
+ 1);
                    updateDayShow();
                }

            }
);
            cbxYear.addItemListener(
new ItemListener() {
                
public void itemStateChanged(ItemEvent e) {
                    updateDayShow();
                }

            }
);
            cbxMonth.addItemListener(
new ItemListener() {
                
public void itemStateChanged(ItemEvent e) {
                    updateDayShow();
                }

            }
);
        }

        
//update the DayPanel according to the selected Year and Month
        private void updateDayShow(){
            Calendar currentDate 
= Calendar.getInstance();
            currentDate.set(Integer.parseInt((String)cbxYear.getSelectedItem()),
                    Integer.parseInt((String)cbxMonth.getSelectedItem()) 
- 1,
                    currentDate.get(Calendar.DAY_OF_MONTH));
            dp.updateShow(currentDate);
        }

        
private void addYearAndMonth(){
            
for (int i = 1900; i < 2045; i++{
                cbxYear.addItem(String.valueOf(i));
            }

            
for (int i = 1; i < 13; i++{
                cbxMonth.addItem(String.valueOf(i));
            }

            Calendar now 
= Calendar.getInstance();
            
//selected the current data defaultly
            cbxYear.setSelectedItem(String.valueOf(now.get(Calendar.YEAR)));
            cbxMonth.setSelectedItem(String.valueOf(now.get(Calendar.MONTH) 
+ 1));
        }


    }

    
//display week information
    class WeekPanel extends JPanel{
        
public WeekPanel(){
            JLabel lblSun,lblMon,lblTues,lblWed,lblThur,lblFri,lblSat;
            lblSun 
= new JLabel("Sun",SwingConstants.CENTER);
            lblMon 
= new JLabel("Mon",SwingConstants.CENTER);
            lblTues 
= new JLabel("Tues",SwingConstants.CENTER);
            lblWed 
= new JLabel("Web",SwingConstants.CENTER);
            lblThur 
= new JLabel("Thur",SwingConstants.CENTER);
            lblFri 
= new JLabel("Fri",SwingConstants.CENTER);
            lblSat 
= new JLabel("Sat",SwingConstants.CENTER);
            lblSun.setForeground(Color.BLUE);
            lblMon.setForeground(Color.BLUE);
            lblTues.setForeground(Color.BLUE);
            lblWed.setForeground(Color.BLUE);
            lblThur.setForeground(Color.BLUE);
            lblFri.setForeground(Color.BLUE);
            lblSat.setForeground(Color.BLUE);
            setLayout(
new GridLayout(1,7));
            add(lblSun);
            add(lblMon);
            add(lblTues);
            add(lblWed);
            add(lblThur);
            add(lblFri);
            add(lblSat);
            setBorder(BorderFactory.createLineBorder(Color.BLUE));
            setPreferredSize(
new Dimension(340,25));
        }

    }

    
//display days of month,according to the month and the year,decided how to list all days
    class DayPanel extends JPanel implements ActionListener{
        JButton[] dayList;
        JButton selectedBtn;
        
public DayPanel(){
            dayList 
= new JButton[42];
            setLayout(
new GridLayout(6,7,0,0));
            
for (int i = 0; i < dayList.length; i++{
                dayList[i] 
= new JButton();
                add(dayList[i]);
                dayList[i].setPreferredSize(
new Dimension(48,25));
            }

            setBorder(BorderFactory.createLineBorder(Color.blue));
            updateShow(Calendar.getInstance());
        }

        
//update view according to the selected year and month
        public void updateShow(Calendar selectedDate){
            
for (int i = 0; i < dayList.length; i++{
                dayList[i].setVisible(
true);
                dayList[i].setForeground(Color.BLACK);
            }

            
int dayOfMonth = selectedDate.get(Calendar.DAY_OF_MONTH);
            selectedDate.set(Calendar.DAY_OF_MONTH,
1);
            
int dayOfWeek = selectedDate.get(Calendar.DAY_OF_WEEK);
            
int[] days = countDay(selectedDate);
            
int currentDay = 0;
            
for (int i = 0; i < days.length; i++{
                
if(days[i] == 0){
                    dayList[i].setVisible(
false);
                }
else{
                    currentDay
++;
                    dayList[i].setText(String.valueOf(currentDay));
                    dayList[i].addActionListener(
this);
                }

            }

            dayList[dayOfMonth 
+ dayOfWeek - 2].setForeground(Color.red);
            repaint();
        }

        
//count the days of the month
        private int[] countDay(Calendar selectedDate){
            
int[] day = new int[42];
            
int oldMonth = selectedDate.get(Calendar.MONTH);
            
int dayOfWeek = selectedDate.get(Calendar.DAY_OF_WEEK);
            
boolean isNextMonth = true;
            
int allDay = 0;
            
while(isNextMonth){
                selectedDate.add(Calendar.DAY_OF_MONTH,
1);
                
if(oldMonth != selectedDate.get(Calendar.MONTH)){
                    isNextMonth 
= false;
                }

                allDay
++;
            }

            
for(int i = 0;i < allDay;i++){
                day[dayOfWeek 
- 1 + i] = 1;
            }

            
return day;
        }

        
//show the selected data in txtShow by java.lang.String 
        public void actionPerformed(ActionEvent e) {
            JButton source 
= (JButton)e.getSource();
            dc.dispose();
            String s 
= cbxYear.getSelectedItem() + "-"
                    
+ cbxMonth.getSelectedItem() + "-"
                    
+ source.getText().trim();
            txtShow.setText(s);
            isShow 
= false;
        }

    }

    
//compose the YearAndMonthPanel,the WeekPanel and the DayPanel into the DateComponent view
    class DateComponent extends JWindow{
        
public DateComponent(){
            Container c 
= getContentPane();
            JPanel pnlMain 
= new JPanel();
            YearAndMonthPanel yamp 
= new YearAndMonthPanel();
            WeekPanel wp 
= new WeekPanel();
            dp 
= new DayPanel();
            pnlMain.add(yamp);
            pnlMain.add(wp);
            pnlMain.add(dp);
            c.add(pnlMain, BorderLayout.CENTER);
            getRootPane().setBorder(BorderFactory.createLineBorder(Color.orange));
            setVisible(
true);
            pack();
            setAlwaysOnTop(
true);
        }

    }

}

原创粉丝点击