文档章节

Swing 自定义日期选择器

扁-哥
 扁-哥
发布于 2015/08/26 15:24
字数 1163
阅读 3086
收藏 2

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

}




© 著作权归作者所有

扁-哥

扁-哥

粉丝 119
博文 42
码字总数 46106
作品 0
西城
高级程序员
私信 提问
JLunarDatePicke r0.1 发布,农历日期选择器

JLunarDatePicker是中国农历日期选择器,是开源的Java Swing包 示例代码: 运行结果: 实例化JLunarDatePicker时,有两个构造函数: 1.JLunarDatePicker(),获取默认风格的日历选择器对象 ...

刘学炜
2013/03/05
2.7K
31
monkeyk7/jcalendarchooser

#jcalendarchooser Java Swing 日期,日期时间选择组件 使用要求: JDK 1.6 + 截图 JCalendarChooser JTimeChooser 说明与使用 JCalendarChooser 封装的日期选择器 使用: 1.创建JCalendarChoo...

monkeyk7
2015/01/06
0
0
layDate 5.0 正式版发布,独立清爽的日期与时间组件

layDate 是 layui 独立维护的三大组件之一(即该版本可独立使用,无需采用 layui),最早发布于2014年6月,但当时只迭代了一个版本,就再也没有更新。而现在,我们对其进行了一次全面的重写,...

贤心
2017/08/25
3.3K
12
9个有用的jQuery日历和网页设计师的日期选择器插件

事件日历和日期选择器是是我们开发当中经常遇到的问题,这个时候我们就需要用jquery插件来实现,昨天我在做项目的时候,遇到了个问题就是如何显示倒计时问题,我这个时候就用jquery插件解决的...

未来十年
2012/01/02
0
0
andorid择器类库,包括日期及时间选择器性别、职业、学历、星座等

andorid择器类库,包括日期及时间选择器性别、职业、学历、星座等 安度博客 » 安度博客2017-05-1827 阅读 Andorid时间星座日期选择器 描述: 安卓选择器类库,包括日期及时间选择器(可设置...

安度博客 » 安度博客
2017/05/18
0
0

没有更多内容

加载失败,请刷新页面

加载更多

c++ 虚基类

c++ 虚基类 p556

天王盖地虎626
27分钟前
41
0
Java中的面向对象

一、面向对象 面向对象和面向过程的区别 过程就是函数,就是写方法,就是方法的一种实现。 对象就是将函数,属性的一种封装。用人们思考习惯的方式思考问题。 如何自定义类 修饰符 类名{ //成...

zhiruochujian
35分钟前
3
0
k8s删除Terminating状态的命名空间

背景: 我们都知道在k8s中namespace有两种常见的状态,即Active和Terminating状态,其中后者一般会比较少见,只有当对应的命名空间下还存在运行的资源,但是该命名空间被删除时才会出现所谓的...

Andy-xu
38分钟前
32
0
seata源码阅读笔记

seata源码阅读笔记 本文没有seata的使用方法,怎么使用seata可以参考官方示例,详细的很。 本文基于v0.8.0版本,本文没贴代码。 seata中的三个重要部分: TC:事务协调器,维护全局事务和分支...

东都大狼狗
51分钟前
21
0
Rust:最小化窗口后 CPU占用率高 (winit,glutin,imgui-rust)

最近试着用 imgui-rust 绘制界面,发现窗口最小化后CPU占用会增大。 查询的资料如下: https://github.com/rust-windowing/winit/issues/783 https://github.com/ocornut/imgui/issues/1151 ...

reter
55分钟前
32
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部