论坛首页 Java企业应用论坛

(最新修改——显示节日)----Java写出来的日历(有显示农历)

浏览 17534 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (4) :: 隐藏帖 (1)
作者 正文
   发表时间:2010-08-12   最后修改:2011-04-22

 

  前言:我总是喜欢看日历,看多了突然萌发出来自己想做个日历出来的想法。本来自己是个程序员(java),目前上班空闲时间也算多;于是从网络上看了看有关怎样用java来实现日历的相关示例及文章,自己就开始动手操作了!不过现在做出来还是有点漏洞:就是程序初始化运行之后,系统当前日期的颜色突出显示问题;当我更换月份、或者是年份后再回到当前的时间,突出显示当前(今天的)时间的颜色会随鼠标的移动而消失;这个让我不解,试了好多中方式都没弄好!希望javaeye的高手们看了后,能帮我解决这个问题……好了废话不多说,马上把源代码贴出。。。(注:Java日历.rar附件是用exe4j打包出来的exe可执行文件,如本机安装了JDK或是有不是安装版JDK的环境变量;都可以直接双击运行查看效果)

           

package org.cal;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;

/**
 * @author  作 者:xfeng 
 * @version 创建时间:2010-5-25 上午11:19:15
 */
@SuppressWarnings("serial")
class DateWin extends JFrame implements ItemListener {
	private Calendar cd = null;
	private int years;
	private int months;
	private int row;
	private int column;
	private int tcr_row;
	private int tcr_column;
	private int listen_tcr_row;
	private int listen_tcr_column;
	private boolean is_in_listener = false;
	private String xingqi = null;
	private JTable table;
	private Object date[][];
	private Object name[] = { "日", "一", "二", "三", "四", "五", "六" };
	private JComboBox year = new JComboBox();
	private JComboBox month = new JComboBox();
	private JLabel label1;
	private JLabel label2;
	private JLabel label3;
	private JLabel label4;
	private JLabel label5;
	private JPanel panel;
	private JPanel rights_panel = forAddEndPanel();
	static SimpleDateFormat chineseDateFormat = new SimpleDateFormat(
			"yyyy年MM月dd日");

	protected void toCenter() {
		Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
		Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
		int screenWidth = screenSize.width / 2; // 获取屏幕的宽
		int screenHeight = screenSize.height / 2; // 获取屏幕的高
		int height = this.getHeight();
		int width = this.getWidth();
		setLocation(screenWidth - width / 2, screenHeight - height / 2);
	}

	public void getDateWin(String s) {
		ImageIcon title = new ImageIcon("images/title_xiong.gif");
		setIconImage(title.getImage());
		setTitle(s);
		setSize(410, 202);
		toCenter();
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		int startYear=1900;
		int endYear=2050;
		cd=Calendar.getInstance();
		int sysYear=cd.get(Calendar.YEAR);
		for (int i = startYear; i < endYear; i++) {
			int years = i;
			if(endYear==sysYear){
				endYear+=10;
			}
			year.addItem(years);
		}
		for (int i = 1; i < 13; i++) {
			month.addItem(i);
		}
		label1 = new JLabel("当前查看:公历 ");
		label2 = new JLabel("年");
		label3 = new JLabel("月");
		panel = new JPanel();
		panel.add(label1);
		panel.add(year);
		panel.add(label2);
		panel.add(month);
		panel.add(label3);
		Container con = getContentPane();
		con.setLayout(new BorderLayout());
		con.add(panel, BorderLayout.NORTH);
		con.add(rights_panel, BorderLayout.SOUTH);
		cd = new GregorianCalendar();
		Calendar cal = Calendar.getInstance();
		years = cd.get(Calendar.YEAR);
		year.setSelectedItem(years);
		months = cd.get(Calendar.MONTH) + 1;
		month.setSelectedItem(months);
		cd.set(Calendar.DATE, 1);
		int dateNumber = cd.getActualMaximum(Calendar.DATE);
		int firstDay = cd.get(Calendar.DAY_OF_WEEK) - 1;
		int count = 1;
		int is_today = cal.get(Calendar.DATE);
		date = new Object[6][7];
		Lunar lunar = null;
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 7; j++) {
				if (count == is_today) {
					tcr_row = i;
					tcr_column = j;
				}
				if (count > dateNumber)
					break;
				else {
					if ((i * 7 + j) < firstDay)
						continue;
					else {
						String today = years + "年" + months + "月" + count + "日";
						Calendar currentDay = Calendar.getInstance();
						try {
							currentDay.setTime(chineseDateFormat.parse(today));
						} catch (ParseException e) {
							e.printStackTrace();
						}
						lunar = new Lunar(currentDay);
						String currentDate = lunar.toString();
						int startIndex = currentDate.length() - 2;
						String showMonth = currentDate.substring(0, startIndex);
						String showDay = currentDate.substring(startIndex);
						if (showDay.equals("初一")) {
							date[i][j] = count + "/" + showMonth;
						} else {
							date[i][j] = count + "/" + showDay;
						}
						count++;
					}
				}
			}
		}
		final String cyclical = "星期" + name[tcr_column] + " 农历"
				+ lunar.cyclical() + "年";
		final String animalsYear = "【" + lunar.animalsYear() + "年】";
		label4 = new JLabel(cyclical);
		label5 = new JLabel(animalsYear);
		panel.add(label4);
		panel.add(label5);
		table = new JTable(date, name);
		table.setRowHeight(15);
		table.setEnabled(false);
		// 设置不能重新调整列宽
		table.getTableHeader().setResizingAllowed(false);
		// 设置不能重新排序各列
		table.getTableHeader().setReorderingAllowed(false);
		con.add(new JScrollPane(table), BorderLayout.CENTER);
		// 标识系统当前时间高亮显示
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column) {
				Component cell = super.getTableCellRendererComponent(table,
						value, isSelected, hasFocus, row, column);
				if (row == tcr_row && column == tcr_column
						&& cell.isBackgroundSet()) {// 设置变色的单元格
					cell.setBackground(Color.red);
				} else {
					cell.setBackground(Color.WHITE);
				}
				return cell;
			}
		};
		// 设置表格单元格内容居中显示
		tcr.setHorizontalAlignment(SwingConstants.CENTER);
		for (int i = 0; i < name.length; i++) {
			table.getColumn(name[i]).setCellRenderer(tcr);
		}
		year.addItemListener(this);
		month.addItemListener(this);
		foMmouseListener(true);
		con.validate();
		validate();
	}

	public void itemStateChanged(ItemEvent e) {
		Calendar cal = Calendar.getInstance();
		years = Integer.parseInt(year.getSelectedItem().toString());
		months = Integer.parseInt(month.getSelectedItem().toString()) - 1;
		cd = new GregorianCalendar(years, months, 1);
		int dateNumber = cd.getActualMaximum(Calendar.DATE);
		int firstDay = cd.get(Calendar.DAY_OF_WEEK) - 1;
		int count = 1;
		int is_year = cal.get(Calendar.YEAR);
		int is_month = cal.get(Calendar.MONTH);
		int is_day = cal.get(Calendar.DAY_OF_MONTH);
		date = new Object[6][7];
		Lunar lunar = null;
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 7; j++) {
				if (years == is_year && months == is_month && count == is_day) {
					is_in_listener = true;
					listen_tcr_row = i;
					listen_tcr_column = j;
					xingqi = "星期" + name[tcr_column] + " ";
				}
				if (count > dateNumber)
					break;
				else {
					if ((i * 7 + j) < firstDay)
						continue;
					else {
						String today = years + "年" + (months + 1) + "月" + count
								+ "日";
						Calendar currentDay = Calendar.getInstance();
						try {
							currentDay.setTime(chineseDateFormat.parse(today));
						} catch (ParseException ex) {
							ex.printStackTrace();
						}
						lunar = new Lunar(currentDay);
						String currentDate = lunar.toString();
						int startIndex = currentDate.length() - 2;
						String showMonth = currentDate.substring(0, startIndex);
						String showDay = currentDate.substring(startIndex);
						if (showDay.equals("初一")) {
							date[i][j] = count + "/" + showMonth;
						} else {
							date[i][j] = count + "/" + showDay;
						}
						count++;
					}
				}
			}
		}
		panel.remove(label4);
		panel.remove(label5);
		final String cyclical = "农历" + lunar.cyclical() + "年";
		final String animalsYear = "【" + lunar.animalsYear() + "年】";
		if (years != is_year || months != is_month) {
			xingqi = null;
		}
		label4 = new JLabel((xingqi == null ? "" : xingqi) + cyclical);
		label5 = new JLabel(animalsYear);
		panel.add(label4);
		panel.add(label5);
		table = new JTable(date, name);
		table.setRowHeight(15);
		table.setEnabled(false);
		// 设置不能重新调整列宽
		table.getTableHeader().setResizingAllowed(false);
		// 设置不能重新排序各列
		table.getTableHeader().setReorderingAllowed(false);
		getContentPane().removeAll();
		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(panel, BorderLayout.NORTH);
		getContentPane().add(rights_panel, BorderLayout.SOUTH);
		getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
		// 标识系统当前时间高亮显示
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int _row, int _column) {
				Component cell = super.getTableCellRendererComponent(table,
						value, isSelected, hasFocus, _row, _column);
				if (is_in_listener && _row == listen_tcr_row
						&& _column == listen_tcr_column
						&& cell.isBackgroundSet()) {// 设置变色的单元格
					cell.setBackground(Color.red);
					is_in_listener = false;
				} else {
					cell.setBackground(Color.white);
				}
				return cell;
			}
		};
		// 设置表格单元格内容居中显示
		tcr.setHorizontalAlignment(SwingConstants.CENTER);
		for (int i = 0; i < name.length; i++) {
			table.getColumn(name[i]).setCellRenderer(tcr);
		}
		foMmouseListener(false);
		getContentPane().validate();
		validate();
	}

	private void foMmouseListener(final boolean is_in_listener) {
		table.addMouseMotionListener(new MouseMotionListener() {
			public void mouseDragged(MouseEvent e) {

			}

			public void mouseMoved(MouseEvent e) {
				Point point = e.getPoint();
				int x = table.rowAtPoint(point);
				int y = table.columnAtPoint(point);
				if (x != row || y != column) {
					row = x;
					column = y;
				}
				Object tip = table.getValueAt(row, column);
				if (tip != null) {
					String tip_str = tip.toString();
					String date_yangli_tip = tip_str.substring(0, tip_str
							.lastIndexOf("/"));
					StringBuffer tipText = new StringBuffer();
					StringBuffer move_currentDay_str = new StringBuffer();
					move_currentDay_str.append(years);
					move_currentDay_str.append("年");
					if (is_in_listener) {
						move_currentDay_str.append(months);
					} else {
						move_currentDay_str.append((months + 1));
					}
					move_currentDay_str.append("月");
					move_currentDay_str.append(date_yangli_tip);
					move_currentDay_str.append("日 ");
					Calendar move_currentDay = Calendar.getInstance();
					try {
						move_currentDay.setTime(chineseDateFormat
								.parse(move_currentDay_str.toString()));
					} catch (ParseException ex) {
						ex.printStackTrace();
					}
					Lunar move_lunar = new Lunar(move_currentDay);
					tipText.append(move_currentDay_str);
					tipText.append("星期");
					tipText.append(name[column] + " ");
					tipText.append("农历");
					tipText.append(move_lunar.toString());
					table.setToolTipText(tipText.toString());
				} else {
					table.setToolTipText("");
				}
			}
		});
	}

	private JPanel forAddEndPanel() {
		JPanel rights_panel = new JPanel();
		JLabel contact_label = new JLabel("联系方式:xiong_jx@foxmail.com");
		JLabel design_name_label = new JLabel("作者:Design By xfeng ");
		contact_label.setFont(new Font("宋体", 0, 12));
		design_name_label.setFont(new Font("宋体", 0, 12));
		contact_label.setForeground(Color.blue);
		design_name_label.setForeground(Color.blue);
		contact_label.setPreferredSize(new java.awt.Dimension(206, 13));
		rights_panel.add(contact_label);
		rights_panel.add(design_name_label);
		return rights_panel;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*----------设置成系统风格---------*/
		try {
			String laf = UIManager.getSystemLookAndFeelClassName();
			UIManager.setLookAndFeel(laf);
		} catch (Exception e) {
			e.printStackTrace();
		}
		DateWin dateWin = new DateWin();
		dateWin.getDateWin("Java日历  - 【xfeng】");
	}
}

 农历显示的类文件是从网上找到的,在这里感谢那位提供者!附件MainCal.rar中的Lunar.java就是提供显示农历的java类;解压MainCal.rar在Myeclipse中直接运行MainDate.java类,也可以查看效果…

   注:根据网友回馈的bug,【农历显示错误】我做了一下修改;上面主程序日历代码也有所变更,想查看更改后的效果:请下载“附件更改”的附件,两个附件是对应之前的;源代码就不贴出来了,请自己看附件吧……

  • Maincal.rar (9.2 KB)
  • 描述: MainCal.rar附件更改
  • 下载次数: 358
  • Java日历.rar (173.3 KB)
  • 描述: Java日历.rar附件更改
  • 下载次数: 520
  • 大小: 55.5 KB
   发表时间:2010-08-12  
写得很不错.我记得跟你同学的时候写过一个坦克大战的游戏.呵呵.好多东西,好多包我都没有再用了.看了一下,回忆很多!
0 请登录后投票
   发表时间:2010-08-12  
看到好多都没用到过,值得看看.
我是JAVA初学者,过来学习学习....
0 请登录后投票
   发表时间:2010-08-12  
那个EXE可执行文件,我双击,怎么打不开。。
0 请登录后投票
   发表时间:2010-08-12  
报错了...
0 请登录后投票
   发表时间:2010-08-12  
LZ,我测试你说的那个问题没有发现有BUG啊,再试试吧,我试的还可以。
意见:要是系统时间换的话,软件时间也跟着换就最好不过了,意见而已。
0 请登录后投票
   发表时间:2010-08-12  
写个与GUI无关的功能对象更好.
GUI层面直接掉用相应的方法即可.
0 请登录后投票
   发表时间:2010-08-13  
万年历不准
0 请登录后投票
   发表时间:2010-08-13  
用的是哪个版本的jdk啊?
0 请登录后投票
   发表时间:2010-08-13  
LZ和我本家人啊..
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics