// 重画组件 private class PaintThread implements Runnable { public void run() { while (true) { repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
/* Calendar.java: Java program to display a calendar for any month * after 1582. The user inputs the year into a TextField and chooses * the month from a Choice object (drop-down combo box), then clicks * 'New Calendar' to show the calendar for that month and year. Call * applet from an HTML file with this tag: * * <applet code>="Calendar.class" width=421 height=481></applet> * * The applet assumes a 421x481 pixel surface on which to draw. */ import java.applet.Applet; import java.awt.*; import java.util.Date;public class Calendar extends Applet { static final int YTOP = 90; /* y-size of margin above calendar box */ static final int YHEADER = 30; /* y-size of horz strip with day names */ static final int NCELLX = 7; /* number of cells across */ static final int CELLSIZE = 60; /* size of each square cell */ static final int MARGIN = 8; /* margin from number to cell top, right */ static final int FEBRUARY = 1; /* special month during leap years */ // Data entry controls at top. Label yearLabel = new Label("Year:"); TextField yearTextField = new TextField("1996", 5); Label monthLabel = new Label("Month:"); Choice monthChoice = new Choice(); Button newCalButton = new Button("New Calendar"); // Date object to get current month and year. Date now = new Date(); // Font for controls at top. Font smallArialFont = new Font("Arial", Font.PLAIN, 15); // Font for for month/year caption above calendar. Font largeArialFont = new Font("Arial", Font.BOLD, 30); String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; String months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; int DaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Month and year entered by user. int userMonth; int userYear; 。。 参考:http://my.execpc.com/~mikeber/calendar.html
去看看java的Calendar类,很容易实现的。
package trade.database.util;/* * DateChooser.java * * Created on 2007年8月22日, 下午6:07 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Point; import java.awt.Polygon; import java.awt.Stroke; import java.awt.Toolkit; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.SwingUtilities; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener;/** * 日期选择面板 * * @author hadeslee */ public class DateChooser extends JPanel { /** * */ private static final long serialVersionUID = 1L; private Date initDate; private Calendar now = Calendar.getInstance(); private Calendar select; private JPanel monthPanel;// 月历 private JP1 jp1;// 四块面板,组成 private JP3 jp3; private Font font = new Font("宋体", Font.PLAIN, 12); private final LabelManager lm = new LabelManager(); private JLabel showDate;// ,toSelect; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); private boolean isShow = false; private Popup pop; /** * Creates a new instance of DateChooser */ public DateChooser() { this(new Date()); } public DateChooser(Date date) { initDate = date; select = Calendar.getInstance(); select.setTime(initDate); initPanel(); initLabel(); } public void setEnabled(boolean b) { super.setEnabled(b); showDate.setEnabled(b); } /** * 得到当前选择框的日期 */ public Date getDate() { return select.getTime(); } /** * 得到当前修改的时候的日期 */ public Date getModifyDate() { java.util.Date modifyDate = null; try { modifyDate = sdf.parse(showDate.getText().toString()); } catch (ParseException e) { System.out.println(); e.printStackTrace(); } return modifyDate; } /** * 设置修改的日期 */ public void setModifyDate(String modifyDateStr){ //保证设置格式为显示的正常模式 2009年2月23日 showDate.setText(modifyDateStr); }
/** * 设置修改的日期 */ public void setModifyDate(Date date){ setModifyDate(sdf.format(date)); } // 根据初始化的日期,初始化面板 private void initPanel() { monthPanel = new JPanel(new BorderLayout()); monthPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE)); JPanel up = new JPanel(new BorderLayout()); up.add(jp1 = new JP1(), BorderLayout.NORTH); up.add(new JP2(), BorderLayout.CENTER); monthPanel.add(jp3 = new JP3(), BorderLayout.CENTER); monthPanel.add(up, BorderLayout.NORTH); monthPanel.add(new JP4(), BorderLayout.SOUTH); this.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { } public void ancestorRemoved(AncestorEvent event) { } // 只要祖先组件一移动,马上就让popup消失 public void ancestorMoved(AncestorEvent event) { hidePanel(); } }); } // 初始化标签 private void initLabel() { showDate = new JLabel(sdf.format(initDate)); showDate.setRequestFocusEnabled(true); showDate.addMouseListener(new MouseAdapter() { public void mousePressed(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(new Dimension(90, 25)); this.setBorder(BorderFactory.createLineBorder(Color.GRAY)); showDate.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { if (showDate.isEnabled()) { showDate.setCursor(new Cursor(Cursor.HAND_CURSOR)); showDate.setForeground(Color.RED); } } public void mouseExited(MouseEvent me) { if (showDate.isEnabled()) { showDate.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); showDate.setForeground(Color.BLACK); } } public void mousePressed(MouseEvent me) { if (showDate.isEnabled()) { showDate.setForeground(Color.CYAN); if (isShow) { hidePanel(); } else { showPanel(showDate); } } } public void mouseReleased(MouseEvent me) { if (showDate.isEnabled()) { showDate.setForeground(Color.BLACK); } } }); showDate.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { hidePanel(); } public void focusGained(FocusEvent e) { } }); } // 根据新的日期刷新 private void refresh() { jp1.updateDate(); jp3.updateDate(); SwingUtilities.updateComponentTreeUI(this); } // 提交日期 private void commit() { System.out.println("选中的日期是:" + sdf.format(select.getTime())); showDate.setText(sdf.format(select.getTime())); hidePanel(); } private void hidePanel() { if (pop != null) { isShow = false; pop.hide(); pop = null; } } private void showPanel(Component owner) { if (pop != null) { pop.hide(); } Point show = new Point(0, showDate.getHeight()); SwingUtilities.convertPointToScreen(show, showDate); Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); int x = show.x; int y = show.y; if (x < 0) { x = 0; } if (x > size.width - 295) { x = size.width - 295; } if (y < size.height - 170) { } else { y -= 188; } pop = PopupFactory.getSharedInstance() .getPopup(owner, monthPanel, x, y); pop.show(); isShow = true; } private class JP1 extends JPanel { /** * */ private static final long serialVersionUID = 1L; JLabel left, right, center; public JP1() { super(new BorderLayout()); this.setBackground(new Color(160, 185, 215)); initJP1(); } private void initJP1() { left = new JLabel(" << ", JLabel.CENTER); left.setToolTipText("上一月"); right = new JLabel(" >> ", JLabel.CENTER); right.setToolTipText("下一月"); left.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); right.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); center = new JLabel("", JLabel.CENTER); updateDate(); this.add(left, BorderLayout.WEST); this.add(center, BorderLayout.CENTER); this.add(right, BorderLayout.EAST); this.setPreferredSize(new Dimension(295, 25)); left.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { left.setCursor(new Cursor(Cursor.HAND_CURSOR)); left.setForeground(Color.RED); } public void mouseExited(MouseEvent me) { left.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); left.setForeground(Color.BLACK); }
public void mousePressed(MouseEvent me) { select.add(Calendar.MONTH, -1); left.setForeground(Color.WHITE); refresh(); } public void mouseReleased(MouseEvent me) { left.setForeground(Color.BLACK); } }); right.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { right.setCursor(new Cursor(Cursor.HAND_CURSOR)); right.setForeground(Color.RED); } public void mouseExited(MouseEvent me) { right.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); right.setForeground(Color.BLACK); } public void mousePressed(MouseEvent me) { select.add(Calendar.MONTH, 1); right.setForeground(Color.WHITE); refresh(); } public void mouseReleased(MouseEvent me) { right.setForeground(Color.BLACK); } }); } private void updateDate() { center.setText(select.get(Calendar.YEAR) + "年" + (select.get(Calendar.MONTH)) + "月"); } } private class JP2 extends JPanel { /** * */ private static final long serialVersionUID = 1L; public JP2() { this.setPreferredSize(new Dimension(295, 20)); } protected void paintComponent(Graphics g) { g.setFont(font); g.drawString("星期日 星期一 星期二 星期三 星期四 星期五 星期六", 5, 10); g.drawLine(0, 15, getWidth(), 15); } } private class JP3 extends JPanel { /** * */ private static final long serialVersionUID = 1L; public JP3() { super(new GridLayout(6, 7)); this.setPreferredSize(new Dimension(295, 100)); initJP3(); } private void initJP3() { updateDate(); } public void updateDate() { this.removeAll(); lm.clear(); Date temp = select.getTime(); Calendar select = Calendar.getInstance(); select.setTime(temp); select.set(Calendar.DAY_OF_MONTH, 1); int index = select.get(Calendar.DAY_OF_WEEK); int sum = (index == 1 ? 8 : index); select.add(Calendar.DAY_OF_MONTH, 0 - sum); for (int i = 0; i < 42; i++) { select.add(Calendar.DAY_OF_MONTH, 1); lm .addLabel(new MyLabel(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); } } private class MyLabel extends JLabel implements Comparator<MyLabel>, MouseListener, MouseMotionListener { /** * */ private static final long serialVersionUID = 1L; private int year, month, day; private boolean isSelected; public MyLabel(int year, int month, int day) { 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(new Color(160, 185, 215)); } else { this.setBackground(Color.WHITE); } } public boolean getIsSelected() { return isSelected; } public void setSelected(boolean b, boolean isDrag) { isSelected = b; if (b && !isDrag) { int temp = select.get(Calendar.MONTH); select.set(year, month, day); if (temp == month) { SwingUtilities.updateComponentTreeUI(jp3); } else { refresh(); } } this.repaint(); } protected void paintComponent(Graphics g) { if (day == select.get(Calendar.DAY_OF_MONTH) && month == select.get(Calendar.MONTH)) { // 如果当前日期是选择日期,则高亮显示 g.setColor(new Color(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 = new Polygon(); 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 = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 1.0f, new float[] { 2.0f, 2.0f }, 1.0f); Graphics2D gd = (Graphics2D) g; gd.setStroke(s); gd.setColor(Color.BLACK); Polygon p = new Polygon(); 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); } public boolean contains(Point p) { return this.getBounds().contains(p); } private void update() { repaint(); } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { isSelected = true; update(); }
public void mouseReleased(MouseEvent e) { Point p = SwingUtilities.convertPoint(this, e.getPoint(), jp3); lm.setSelect(p, false); commit(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { Point p = SwingUtilities.convertPoint(this, e.getPoint(), jp3); lm.setSelect(p, true); } public void mouseMoved(MouseEvent e) { } public int compare(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); return c1.compareTo(c2); } } private class LabelManager { private List<MyLabel> list; public LabelManager() { list = new ArrayList<MyLabel>(); } public List<MyLabel> getLabels() { return list; } public void addLabel(MyLabel my) { list.add(my); } public void clear() { list.clear(); } public void setSelect(MyLabel my, boolean b) { for (MyLabel m : list) { if (m.equals(my)) { m.setSelected(true, b); } else { m.setSelected(false, b); } } } public void setSelect(Point p, boolean b) { // 如果是拖动,则要优化一下,以提高效率 if (b) { // 表示是否能返回,不用比较完所有的标签,能返回的标志就是把上一个标签和 // 将要显示的标签找到了就可以了 boolean findPrevious = false, findNext = false; for (MyLabel m : list) { if (m.contains(p)) { findNext = true; if (m.getIsSelected()) { findPrevious = true; } else { m.setSelected(true, b); } } else if (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; } else if (m.getIsSelected()) { m.setSelected(false, b); } } if (temp != null) { temp.setSelected(true, b); } } } } private class JP4 extends JPanel { /** * */ private static final long serialVersionUID = 1L; public JP4() { super(new BorderLayout()); this.setPreferredSize(new Dimension(295, 20)); this.setBackground(new Color(160, 185, 215)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); final JLabel jl = new JLabel("今天: " + sdf.format(new Date())); jl.setToolTipText("点击回到今天日期"); this.add(jl, BorderLayout.CENTER); jl.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { jl.setCursor(new Cursor(Cursor.HAND_CURSOR)); jl.setForeground(Color.RED); } public void mouseExited(MouseEvent me) { jl.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); jl.setForeground(Color.BLACK); } public void mousePressed(MouseEvent me) { jl.setForeground(Color.WHITE); select.setTime(new Date()); refresh(); commit(); } public void mouseReleased(MouseEvent me) { jl.setForeground(Color.BLACK); } }); } } public static void main(String[] args) { final DateChooser mp = new DateChooser(); JFrame jf = new JFrame("test"); jf.add(mp, BorderLayout.CENTER); jf.add(new JButton("测试用的"), BorderLayout.NORTH); jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public JLabel getShowDate() { return showDate; } }
看看几个关于日期的类,做个Demo玩玩算了
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.regex.Pattern;import javax.swing.*;
public class Demo28 extends JFrame { int m = 1;
String[] monthchoose = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12" }; // 存放月份的字符数组 String[] columnNames = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; // 存放星期的字符数组
Calendar ca = Calendar.getInstance();
Container contentPane = getContentPane();
Vector<String> vector = new Vector<String>();
String[][] date = new String[6][7]; // 表格的显示数据的格式
TextField tf; // 文本框的值代表的是年份
JComboBox jb;
JTable table; // 把日期用table的方式显示出来 public void getDate(String year, String month, String week, int Max_Day) {
int n = 0, b = 0; // 动态把传进来月份的天数存放到容器里
for (int j = 1; j <= Max_Day; j++) {
vector.add(String.valueOf(j));
} //每次往table里添加数据的时候,都预先把原table里 的 数据清空
for(int x = 0;x<date.length;x++){
for(int y = 0;y<date[x].length;y++){
date[x][y] = null;
}
}
// 根据传进来月份的第一天是星期几,来构建Table
for (int a = Integer.parseInt(week) - 1; a < date[0].length; a++) {
date[0][a] = new String((String) vector.toArray()[n]);
n++;
} for (int i = 1; i < date.length; i++) {
for (int j = 0; j < date[i].length; j++) {
if (n < vector.size()) {
date[i][j] = new String((String) vector.toArray()[n]);
n++;
} else
break;
}
}
// 把容器里的数据全部清除,以备下次再存放新的数据
while (b < vector.size()) {
vector.remove(b);
}
} public void chooseDate(String day) {
JLabel label = new JLabel(); for (int y = 0; y < date.length; y++) {
for (int z = 0; z < date[y].length; z++) {
System.out.print(date[y][z] + " ");
System.out.println(day);
if (date[y][z] != null) {
if (date[y][z].equals(day)) {
table.setSelectionBackground(Color.yellow);
return;
}
}
}
}
} public void paint() {
setTitle("日历");
setBounds(200, 200, 350, 178);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
int m = 0;
String year = String.valueOf(ca.get(Calendar.YEAR)); // 得到当前的系统时间的年份,并把这个数值存放到year这个变量里
String month = String.valueOf(ca.get(Calendar.MONTH) + 1); // 得到当前的系统时间的月份,并把这个数值存放到month这个变量里
String day = String.valueOf(ca.get(Calendar.DATE)); // 得到当前的系统时间的日期,并把这个数值存放到day这个变量里 ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1
String week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几
int Max_Day = ca.getActualMaximum(Calendar.DATE); // 得到当前系统时间月份有多少天
getDate(year, month, week, Max_Day); // 从月份数组里取出与当前系统时间一样的月份值
for (int i = 0; i < monthchoose.length; i++) {
if (monthchoose[i].equals(month)) {
m = i;
}
} JToolBar toolBar = new JToolBar();
JButton b1 = new JButton("<");
b1.addMouseListener(new myMouseListener1());
JButton b2 = new JButton(">");
b2.addMouseListener(new myMouseListener2());
JLabel j1 = new JLabel("年");
JLabel j2 = new JLabel("月");
tf = new TextField(5);
tf.addKeyListener(new myKeyListener());
tf.setText(year);
jb = new JComboBox(monthchoose);
jb.setSelectedIndex(m);
jb.addActionListener(new myActionListener3()); table = new JTable(date, columnNames);
//table.addMouseListener(new tableMouseListener());
table.setPreferredScrollableViewportSize(new Dimension(350, 150));
JScrollPane jsp = new JScrollPane(table);
contentPane.add(jsp, BorderLayout.CENTER); chooseDate(day); toolBar.add(b1);
toolBar.add(tf);
toolBar.add(b2);
toolBar.add(j1);
toolBar.add(jb);
toolBar.add(j2);
toolBar.setLocation(0, 0);
toolBar.setSize(400, 15);
contentPane.add(toolBar, BorderLayout.NORTH); setVisible(true);
new Thread(new PaintThread()).start(); // 调用内部类PaintThread,根据里面的设置来重画 } public static void main(String[] args) {
Demo28 d28 = new Demo28();
d28.paint();
} // 鼠标单击左边按钮触发的事件
class myMouseListener1 extends MouseAdapter { public void mouseClicked(MouseEvent e) {
String str = tf.getText().trim(); // 得到文本框的值
int i = Integer.parseInt(str);
i = i - 1;
tf.setText(String.valueOf(i));
String new_year = String.valueOf(i); // 把表示年份的文本框的值存放到变量new_year里
ca.set(Calendar.YEAR, i); // 把Calendar 对象的YEAR设置为用户设置的年份
String new_month = (String) jb.getSelectedItem(); // 得到月份值
ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的MONTH设置为用户设置的月份
ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1
String new_week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几
int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天
getDate(new_year, new_month, new_week, Max_Day);
}
}
class myKeyListener extends KeyAdapter { public void keyReleased(KeyEvent e) {
try {
int i = Integer.parseInt(tf.getText().trim());
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
String new_year = String.valueOf(i);
ca.set(Calendar.YEAR, i); // 把Calendar对象的YEAR设置为用户设置的年份
String new_month = (String) jb.getSelectedItem(); // 得到月份值
ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的MONTH设置为用户设置的月份
ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1
String new_week = String.valueOf(ca
.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几
int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天
getDate(new_year, new_month, new_week, Max_Day);
}
} catch (NumberFormatException excption) {
System.out.println("你输入的年份不正确!");
} } }
// 鼠标单击右边按钮触发的事件
class myMouseListener2 extends MouseAdapter { public void mouseClicked(MouseEvent e) {
String str = tf.getText().trim();
int i = Integer.parseInt(str);
i = i + 1;
tf.setText(String.valueOf(i));
String new_year = String.valueOf(i); // 把表示年份的文本框的值存放到变量new_year里
ca.set(Calendar.YEAR, i); // 把Calendar 对象的YEAR设置为用户设置的年份
String new_month = (String) jb.getSelectedItem(); // 得到月份值
ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的MONTH设置为用户设置的月份
ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1
String new_week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几
int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天
getDate(new_year, new_month, new_week, Max_Day);
}
} // 鼠标单击选择框触发的事件
class myActionListener3 implements ActionListener { public void actionPerformed(ActionEvent e) { String new_year = String.valueOf(ca.get(Calendar.YEAR)); // 把表示年份的文本框的值存放到变量new_year里
String new_month = (String) jb.getSelectedItem(); // 得到用户设置的月份
ca.set(Calendar.MONTH, Integer.parseInt(new_month) - 1); // 把Calendar对象的月份值设置为用户定义的月份
ca.set(Calendar.DATE, 1); // 把Calendar 对象的DATA设置为1
String new_week = String.valueOf(ca.get(Calendar.DAY_OF_WEEK)); // 根据设置的Calendar对象,计算出这个月第一天是星期几
int Max_Day = ca.getActualMaximum(Calendar.DATE); // 根据设置后的Calendar对象计算这个月份有多少天
getDate(new_year, new_month, new_week, Max_Day);
}
}
// 重画组件
private class PaintThread implements Runnable { public void run() {
while (true) {
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
* after 1582. The user inputs the year into a TextField and chooses
* the month from a Choice object (drop-down combo box), then clicks
* 'New Calendar' to show the calendar for that month and year. Call
* applet from an HTML file with this tag:
*
* <applet code>="Calendar.class" width=421 height=481></applet>
*
* The applet assumes a 421x481 pixel surface on which to draw.
*/
import java.applet.Applet;
import java.awt.*;
import java.util.Date;public class Calendar extends Applet
{
static final int YTOP = 90; /* y-size of margin above calendar box */
static final int YHEADER = 30; /* y-size of horz strip with day names */
static final int NCELLX = 7; /* number of cells across */
static final int CELLSIZE = 60; /* size of each square cell */
static final int MARGIN = 8; /* margin from number to cell top, right */
static final int FEBRUARY = 1; /* special month during leap years */ // Data entry controls at top.
Label yearLabel = new Label("Year:");
TextField yearTextField = new TextField("1996", 5);
Label monthLabel = new Label("Month:");
Choice monthChoice = new Choice();
Button newCalButton = new Button("New Calendar"); // Date object to get current month and year.
Date now = new Date(); // Font for controls at top.
Font smallArialFont = new Font("Arial", Font.PLAIN, 15);
// Font for for month/year caption above calendar.
Font largeArialFont = new Font("Arial", Font.BOLD, 30); String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}; String months[] = {"January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"}; int DaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Month and year entered by user.
int userMonth;
int userYear;
。。
参考:http://my.execpc.com/~mikeber/calendar.html
* DateChooser.java
*
* Created on 2007年8月22日, 下午6:07
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;/**
* 日期选择面板
*
* @author hadeslee
*/
public class DateChooser extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private Date initDate;
private Calendar now = Calendar.getInstance();
private Calendar select;
private JPanel monthPanel;// 月历
private JP1 jp1;// 四块面板,组成
private JP3 jp3;
private Font font = new Font("宋体", Font.PLAIN, 12);
private final LabelManager lm = new LabelManager();
private JLabel showDate;// ,toSelect;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
private boolean isShow = false;
private Popup pop; /**
* Creates a new instance of DateChooser
*/
public DateChooser() {
this(new Date());
} public DateChooser(Date date) {
initDate = date;
select = Calendar.getInstance();
select.setTime(initDate);
initPanel();
initLabel();
} public void setEnabled(boolean b) {
super.setEnabled(b);
showDate.setEnabled(b);
} /**
* 得到当前选择框的日期
*/
public Date getDate() {
return select.getTime();
} /**
* 得到当前修改的时候的日期
*/
public Date getModifyDate() {
java.util.Date modifyDate = null;
try {
modifyDate = sdf.parse(showDate.getText().toString());
} catch (ParseException e) {
System.out.println();
e.printStackTrace();
}
return modifyDate;
}
/**
* 设置修改的日期
*/
public void setModifyDate(String modifyDateStr){
//保证设置格式为显示的正常模式 2009年2月23日
showDate.setText(modifyDateStr);
}
/**
* 设置修改的日期
*/
public void setModifyDate(Date date){
setModifyDate(sdf.format(date));
} // 根据初始化的日期,初始化面板
private void initPanel() {
monthPanel = new JPanel(new BorderLayout());
monthPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JPanel up = new JPanel(new BorderLayout());
up.add(jp1 = new JP1(), BorderLayout.NORTH);
up.add(new JP2(), BorderLayout.CENTER);
monthPanel.add(jp3 = new JP3(), BorderLayout.CENTER);
monthPanel.add(up, BorderLayout.NORTH);
monthPanel.add(new JP4(), BorderLayout.SOUTH);
this.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) { } public void ancestorRemoved(AncestorEvent event) { } // 只要祖先组件一移动,马上就让popup消失 public void ancestorMoved(AncestorEvent event) {
hidePanel();
} });
} // 初始化标签
private void initLabel() {
showDate = new JLabel(sdf.format(initDate));
showDate.setRequestFocusEnabled(true);
showDate.addMouseListener(new MouseAdapter() {
public void mousePressed(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(new Dimension(90, 25));
this.setBorder(BorderFactory.createLineBorder(Color.GRAY));
showDate.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) { if (showDate.isEnabled()) {
showDate.setCursor(new Cursor(Cursor.HAND_CURSOR));
showDate.setForeground(Color.RED);
}
} public void mouseExited(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
showDate.setForeground(Color.BLACK);
}
} public void mousePressed(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setForeground(Color.CYAN);
if (isShow) {
hidePanel();
} else {
showPanel(showDate);
}
}
} public void mouseReleased(MouseEvent me) {
if (showDate.isEnabled()) {
showDate.setForeground(Color.BLACK);
}
}
});
showDate.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
hidePanel();
} public void focusGained(FocusEvent e) { }
});
} // 根据新的日期刷新
private void refresh() {
jp1.updateDate();
jp3.updateDate();
SwingUtilities.updateComponentTreeUI(this);
} // 提交日期
private void commit() {
System.out.println("选中的日期是:" + sdf.format(select.getTime()));
showDate.setText(sdf.format(select.getTime()));
hidePanel();
} private void hidePanel() {
if (pop != null) {
isShow = false;
pop.hide();
pop = null;
}
} private void showPanel(Component owner) {
if (pop != null) {
pop.hide();
}
Point show = new Point(0, showDate.getHeight()); SwingUtilities.convertPointToScreen(show, showDate);
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
int x = show.x;
int y = show.y;
if (x < 0) {
x = 0;
}
if (x > size.width - 295) {
x = size.width - 295;
}
if (y < size.height - 170) {
} else {
y -= 188;
}
pop = PopupFactory.getSharedInstance()
.getPopup(owner, monthPanel, x, y);
pop.show();
isShow = true;
} private class JP1 extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel left, right, center; public JP1() {
super(new BorderLayout());
this.setBackground(new Color(160, 185, 215));
initJP1();
} private void initJP1() {
left = new JLabel(" << ", JLabel.CENTER);
left.setToolTipText("上一月");
right = new JLabel(" >> ", JLabel.CENTER);
right.setToolTipText("下一月"); left.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
right.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
center = new JLabel("", JLabel.CENTER);
updateDate();
this.add(left, BorderLayout.WEST);
this.add(center, BorderLayout.CENTER);
this.add(right, BorderLayout.EAST);
this.setPreferredSize(new Dimension(295, 25));
left.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
left.setCursor(new Cursor(Cursor.HAND_CURSOR));
left.setForeground(Color.RED);
} public void mouseExited(MouseEvent me) {
left.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
left.setForeground(Color.BLACK);
}
public void mousePressed(MouseEvent me) {
select.add(Calendar.MONTH, -1); left.setForeground(Color.WHITE);
refresh();
} public void mouseReleased(MouseEvent me) {
left.setForeground(Color.BLACK);
}
});
right.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
right.setCursor(new Cursor(Cursor.HAND_CURSOR));
right.setForeground(Color.RED);
} public void mouseExited(MouseEvent me) {
right.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
right.setForeground(Color.BLACK);
} public void mousePressed(MouseEvent me) {
select.add(Calendar.MONTH, 1);
right.setForeground(Color.WHITE);
refresh();
} public void mouseReleased(MouseEvent me) {
right.setForeground(Color.BLACK);
}
});
} private void updateDate() {
center.setText(select.get(Calendar.YEAR) + "年"
+ (select.get(Calendar.MONTH)) + "月");
}
} private class JP2 extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L; public JP2() {
this.setPreferredSize(new Dimension(295, 20));
} protected void paintComponent(Graphics g) {
g.setFont(font);
g.drawString("星期日 星期一 星期二 星期三 星期四 星期五 星期六", 5, 10);
g.drawLine(0, 15, getWidth(), 15);
}
} private class JP3 extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L; public JP3() {
super(new GridLayout(6, 7));
this.setPreferredSize(new Dimension(295, 100));
initJP3();
} private void initJP3() {
updateDate();
} public void updateDate() {
this.removeAll();
lm.clear();
Date temp = select.getTime();
Calendar select = Calendar.getInstance();
select.setTime(temp);
select.set(Calendar.DAY_OF_MONTH, 1);
int index = select.get(Calendar.DAY_OF_WEEK);
int sum = (index == 1 ? 8 : index);
select.add(Calendar.DAY_OF_MONTH, 0 - sum);
for (int i = 0; i < 42; i++) {
select.add(Calendar.DAY_OF_MONTH, 1);
lm
.addLabel(new MyLabel(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);
}
} private class MyLabel extends JLabel implements Comparator<MyLabel>,
MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private int year, month, day;
private boolean isSelected; public MyLabel(int year, int month, int day) { 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(new Color(160, 185, 215));
} else {
this.setBackground(Color.WHITE);
}
} public boolean getIsSelected() {
return isSelected;
} public void setSelected(boolean b, boolean isDrag) {
isSelected = b;
if (b && !isDrag) {
int temp = select.get(Calendar.MONTH);
select.set(year, month, day);
if (temp == month) { SwingUtilities.updateComponentTreeUI(jp3);
} else {
refresh();
}
}
this.repaint();
} protected void paintComponent(Graphics g) {
if (day == select.get(Calendar.DAY_OF_MONTH)
&& month == select.get(Calendar.MONTH)) {
// 如果当前日期是选择日期,则高亮显示
g.setColor(new Color(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 = new Polygon();
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 = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL, 1.0f,
new float[] { 2.0f, 2.0f }, 1.0f);
Graphics2D gd = (Graphics2D) g;
gd.setStroke(s);
gd.setColor(Color.BLACK);
Polygon p = new Polygon();
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);
} public boolean contains(Point p) {
return this.getBounds().contains(p);
} private void update() {
repaint();
} public void mouseClicked(MouseEvent e) {
} public void mousePressed(MouseEvent e) {
isSelected = true;
update();
}
public void mouseReleased(MouseEvent e) {
Point p = SwingUtilities.convertPoint(this, e.getPoint(), jp3);
lm.setSelect(p, false);
commit();
} public void mouseEntered(MouseEvent e) {
} public void mouseExited(MouseEvent e) {
} public void mouseDragged(MouseEvent e) {
Point p = SwingUtilities.convertPoint(this, e.getPoint(), jp3);
lm.setSelect(p, true);
} public void mouseMoved(MouseEvent e) {
} public int compare(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);
return c1.compareTo(c2);
}
} private class LabelManager {
private List<MyLabel> list; public LabelManager() {
list = new ArrayList<MyLabel>();
} public List<MyLabel> getLabels() {
return list;
} public void addLabel(MyLabel my) {
list.add(my);
} public void clear() {
list.clear();
} public void setSelect(MyLabel my, boolean b) {
for (MyLabel m : list) {
if (m.equals(my)) {
m.setSelected(true, b);
} else {
m.setSelected(false, b);
}
}
} public void setSelect(Point p, boolean b) {
// 如果是拖动,则要优化一下,以提高效率
if (b) {
// 表示是否能返回,不用比较完所有的标签,能返回的标志就是把上一个标签和
// 将要显示的标签找到了就可以了
boolean findPrevious = false, findNext = false;
for (MyLabel m : list) {
if (m.contains(p)) {
findNext = true;
if (m.getIsSelected()) {
findPrevious = true;
} else {
m.setSelected(true, b);
}
} else if (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;
} else if (m.getIsSelected()) {
m.setSelected(false, b);
}
}
if (temp != null) {
temp.setSelected(true, b);
}
}
} } private class JP4 extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L; public JP4() {
super(new BorderLayout());
this.setPreferredSize(new Dimension(295, 20));
this.setBackground(new Color(160, 185, 215));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
final JLabel jl = new JLabel("今天: " + sdf.format(new Date()));
jl.setToolTipText("点击回到今天日期");
this.add(jl, BorderLayout.CENTER);
jl.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
jl.setCursor(new Cursor(Cursor.HAND_CURSOR));
jl.setForeground(Color.RED);
} public void mouseExited(MouseEvent me) {
jl.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
jl.setForeground(Color.BLACK);
} public void mousePressed(MouseEvent me) {
jl.setForeground(Color.WHITE);
select.setTime(new Date());
refresh();
commit();
} public void mouseReleased(MouseEvent me) {
jl.setForeground(Color.BLACK);
}
});
}
} public static void main(String[] args) {
final DateChooser mp = new DateChooser();
JFrame jf = new JFrame("test");
jf.add(mp, BorderLayout.CENTER);
jf.add(new JButton("测试用的"), BorderLayout.NORTH);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} public JLabel getShowDate() {
return showDate;
}
}