Swing 自定义日期选择控件

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
Swing日期选择器 采用触发事件的方式,这样的话,就可以将DateChooser添加到任何组件之上, 任何组件都可以捕获日期选择的事件,然后进行相应处理

1. 如何对事件进行管理,可以查看这个 http://my.oschina.net/abian/blog/497296

截图:

package unit;
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.EventListener;
import java.util.GregorianCalendar;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.EventListenerList;
 
/**
 * 日期选择器 采用触发事件的方式,这样的话,就可以将DateChooser添加到任何组件之上,
 * 任何组件都可以捕获日期选择的事件,然后进行相应处理
 * 
 * @author changwen
 * @date Aug 26, 2015
 */
 
@SuppressWarnings("all")
public class DateChooser extends JPanel {
 
    protected Color weekBackgroundColor = new Color(189, 235, 238);
    protected Color weekendBtnFontColor = new Color(240, 64, 64); // color
    protected Color selectedColor = weekBackgroundColor;
    protected Font labelFont = new Font("Arial", Font.PLAIN, 10);
    protected Color defaultBtnFontColor = Color.BLACK;
    protected Color defaultBtnBackgroundColor = Color.WHITE;
    private Calendar cal = null;
    private Calendar todayCal = null;
    private int year;
    private int month;
    private int day;
    private JPanel controllPanel = null;
    private JPanel dateContainerPanel = null;
    private JLabel todayLabel = null;
    protected DateButton[][] buttonDays = null;
    public JComboBox monthChoice;
    public JComboBox yearChoice;
    protected String[] weekTitle = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    protected int[] months = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    private EventListenerList actionListenerList = new EventListenerList();
 
    public DateChooser() {
        buttonDays = new DateButton[6][7];
        cal = Calendar.getInstance();
        todayCal = Calendar.getInstance();
        this.year = cal.get(Calendar.YEAR);
        this.month = cal.get(Calendar.MONTH);
        this.day = cal.get(Calendar.DATE);
        JPanel oprPanel = createControlPanel();
        this.setLayout(new BorderLayout(0, 0));
        dateContainerPanel = new JPanel();
        createDayPanel(cal);
        setActiveDay(day);
        this.add(oprPanel, BorderLayout.NORTH);
        this.add(dateContainerPanel, BorderLayout.CENTER);
 
    }
 
    @SuppressWarnings("all")
    public JPanel createControlPanel() {
        controllPanel = new JPanel();
        controllPanel.setBackground(Color.WHITE);
        Box hBox = Box.createHorizontalBox();
        String strToday = formatDate(todayCal);
        todayLabel = new JLabel(strToday);
        monthChoice = new JComboBox();
        for (int i = 0; i < months.length; i++) {
            monthChoice.addItem(months[i]);
        }
 
        monthChoice.setSelectedItem(months[month]);
        monthChoice.setPreferredSize(new Dimension(monthChoice.getPreferredSize().width,
                monthChoice.getPreferredSize().height));
 
        monthChoice.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                int i = monthChoice.getSelectedIndex();
                if (i >= 0) {
                    month = i;
                    Calendar cal = new GregorianCalendar(year, month, 1);
                    year = cal.get(Calendar.YEAR);
                    month = cal.get(Calendar.MONTH);
                    createDayPanel(cal);
                }
            }
        });
        int currentYear = todayCal.get(Calendar.YEAR);
        final int gapYears = 10;
        yearChoice = new JComboBox();
        for (int i = currentYear - gapYears; i < currentYear + gapYears; i++) {
            yearChoice.addItem(i);
        }
 
        yearChoice.setSelectedIndex(gapYears);
        yearChoice.setPreferredSize(new Dimension(yearChoice.getPreferredSize().width,
                yearChoice.getPreferredSize().height));
 
        yearChoice.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.out.println(yearChoice.getSelectedIndex());
                if (yearChoice.getSelectedIndex() != gapYears) {
                    Integer selYear = (Integer) yearChoice.getSelectedItem();
                    Calendar cal = new GregorianCalendar(year, month, 1);
                    cal.set(Calendar.YEAR, selYear);
                    year = cal.get(Calendar.YEAR);
                    month = cal.get(Calendar.MONTH);
                    createDayPanel(cal);
                }
            }
        });
 
        hBox.add(todayLabel);
        hBox.add(Box.createHorizontalStrut(5));
        hBox.add(monthChoice);
        hBox.add(Box.createHorizontalStrut(8));
        hBox.add(yearChoice);
        hBox.add(Box.createHorizontalStrut(8));
 
        controllPanel.add(hBox, BorderLayout.NORTH);
        return controllPanel;
 
    }
 
    /**
     * 创建日期组件
     * 
     * @param cal
     *            void
     */
    public void createDayPanel(Calendar cal) {
        dateContainerPanel.removeAll();
        dateContainerPanel.revalidate();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        int weeks = cal.get(Calendar.WEEK_OF_MONTH);
 
        GridLayout grid = new GridLayout(7, 7, 0, 0);
        dateContainerPanel.setLayout(grid);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        System.out.println("weekday+" + weekday);
        cal.add(Calendar.DAY_OF_MONTH, 1 - weekday);
        System.out.println("Calendar.DAY_OF_MONTH=" + cal.get(Calendar.DAY_OF_MONTH));
 
        for (int i = 0; i < 7; i++) {
            JLabel weekLabel = new JLabel(weekTitle[i], SwingConstants.CENTER);
            weekLabel.setFont(labelFont);
            weekLabel.setOpaque(true);
            weekLabel.setBackground(weekBackgroundColor);
            dateContainerPanel.add(weekLabel);
        }
        DayButtonActionListener dayButtonActionListener = new DayButtonActionListener();
 
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                int curMonth = cal.get(Calendar.MONTH);
                DateButton button = null;
                if (curMonth != month) {
                    button = new DateButton(" ");
                    button.setEnabled(false);
                    button.setBackground(defaultBtnBackgroundColor);
                } else {
                    int currentDay = cal.get(Calendar.DAY_OF_MONTH);
                    button = new DateButton(currentDay + "");
                    button.setHorizontalTextPosition(SwingConstants.RIGHT);
                    button.setFont(labelFont);
                    button.setBackground(defaultBtnBackgroundColor);
                    button.setSelectedBackground(weekBackgroundColor);
                    if (currentDay == todayCal.get(Calendar.DAY_OF_MONTH) && month == todayCal.get(Calendar.MONTH)
                            && year == todayCal.get(Calendar.YEAR)) {
                        button.setBorder(BorderFactory.createLineBorder(weekendBtnFontColor));
                    }
                    if (cal.get(Calendar.MONTH) != month) {
                        button.setForeground(Color.BLUE);
                    }
                    if (j == 0 || j == 6) {
                        button.setForeground(weekendBtnFontColor);
                    } else {
                        button.setForeground(defaultBtnFontColor);
                    }
 
                }
                button.addActionListener(dayButtonActionListener);
                buttonDays[i][j] = button;
                dateContainerPanel.add(buttonDays[i][j]);
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
 
    }
 
    /**
     * 选中莫一天
     * 
     * @param selectedDay
     *            void
     */
    public void setActiveDay(int selectedDay) {
        clearAllActiveDay();
        if (selectedDay <= 0) {
            day = new GregorianCalendar().get(Calendar.DAY_OF_MONTH);
        } else {
            day = selectedDay;
        }
        int leadGap = new GregorianCalendar(year, month, 1).get(Calendar.DAY_OF_WEEK) - 1;
        JButton selectedButton = buttonDays[(leadGap + selectedDay - 1) / 7][(leadGap + selectedDay - 1) % 7];
        selectedButton.setBackground(weekBackgroundColor);
    }
 
    /**
     * 清除所有选择的日期
     * 
     */
    public void clearAllActiveDay() {
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                JButton button = buttonDays[i][j];
                if (button.getText() != null && button.getText().trim().length() > 0) {
                    button.setBackground(defaultBtnBackgroundColor);
                    button.revalidate();
                }
            }
 
        }
    }
 
    /**
     * 获取选中的日期
     * 
     * @return String
     */
    public String getSelectedDate() {
        Calendar cal = new GregorianCalendar(year, month, day);
        return formatDate(cal);
    }
 
    private String formatDate(Calendar cal) {
        String pattern = "MM-dd-yyyy";
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(cal.getTime());
    }
 
    class DayButtonActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton) e.getSource();
            if (button.getText() != null && button.getText().trim().length() > 0) {
                day = Integer.parseInt(button.getText());
                setActiveDay(day);
                fireActionPerformed(e);// fire button click event
                /**
                 * 采用触发事件的方式,这样的话,就可以将DateChooser添加到任何组件之上,
                 * 任何组件都可以捕获日期选择的事件,然后进行相应处理
                 */
            }
        }
    }
 
    public void addActionListener(ActionListener actionListener) {
        actionListenerList.add(ActionListener.class, actionListener);
    }
 
    public void removeActionListener(ActionListener actionListener) {
        actionListenerList.remove(ActionListener.class, actionListener);
    }
 
    /**
     * 事件管理,触发事件
     * 
     * @param actionEvent
     *            void
     */
    protected void fireActionPerformed(ActionEvent actionEvent) {
        EventListener listenerList[] = actionListenerList.getListeners(ActionListener.class);
        for (int i = 0, n = listenerList.length; i < n; i++) {
            ((ActionListener) listenerList[i]).actionPerformed(actionEvent);
        }
    }
 
    public static void main(String[] args) {
 
        JFrame frame = new JFrame("xxxxxx");
        frame.setSize(400, 300);
 
        final DateChooser datePicker = new DateChooser();
        datePicker.addActionListener(new ActionListener() {// 事件捕获
 
                    public void actionPerformed(ActionEvent e) {
                        System.out.println(datePicker.getSelectedDate());
 
                    }
                });
        frame.getContentPane().add(datePicker);
 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
 
    }
 
}
 
//-------自定义按钮--------------
package unit;
 
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
 
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
 
public class DateButton extends JButton {
    private static final long serialVersionUID = 1L;
    protected Color normalBackground;
    protected Color selectedBackground;
    public DateButton() {
        initAttributes();
    }
 
    public DateButton(Icon icon) {
        super(icon);
        initAttributes();
    }
 
    public DateButton(String text, Icon icon) {
        super(text, icon);
        initAttributes();
    }
 
    public DateButton(String text) {
        super(text);
        initAttributes();
    }
 
    public DateButton(Action a) {
        super(a);
        initAttributes();
    }
 
    public void initAttributes() {
        setRolloverEnabled(true);
        setBorder(BorderFactory.createEmptyBorder());
        setContentAreaFilled(false);
        setFocusPainted(false);
        setNormalBackground(new Color(216, 216, 216));
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }
 
    @Override
    public void paint(Graphics g) {
         
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 
        Paint oldPaint = g2d.getPaint();
         
        if ((getModel().isSelected() || getModel().isPressed()) && selectedBackground != null) {
            g2d.setPaint(selectedBackground);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        } else if (getNormalBackground() != null) {
            g2d.setPaint(getNormalBackground());
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }
        g2d.setPaint(oldPaint);
        super.paint(g2d);
 
    }
 
    public void clearDefaultAttribute() {
        setNormalBackground(null);
    }
 
    @Override
    public void setBackground(Color bg) {
        super.setBackground(bg);
        normalBackground = bg;
    }
 
    public Color getNormalBackground() {
        return normalBackground;
    }
 
    public void setNormalBackground(Color normalBackground) {
        super.setBackground(normalBackground);
        this.normalBackground = normalBackground;
    }
 
     
 
    public void setSelectedBackground(Color selectedBackground) {
        this.selectedBackground = selectedBackground;
    }
 
}

来自:http://my.oschina.net/abian/blog/497331

标签: isp seo

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Python list根据下标删除元素

下一篇:Python用户定义类实现