分享
 
 
 

JAVA基础应用:日期时间选择控件(代码)

王朝java/jsp·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

一次项目研发中需要日期时间选择控件,网上提供的不多,且质量一般,所以只好自己做,参考了网上某位同学的作品Jave日期选择控件DateChooser 。目前的代码将日期时间选择封装在一个按钮组件内,应该很好用,支持Application 、Applet

CODE:

import Java.util.Date;

import java.util.Calendar;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.text.ParseException ;

import java.awt.Color ;

import java.awt.Font;

import java.awt.Point ;

import java.awt.Dimension ;

import java.awt.BorderLayout ;

import java.awt.FlowLayout ;

import java.awt.GridLayout ;

import java.awt.Component ;

import java.awt.Cursor ;

import java.awt.Frame ;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

//import javax.swing.JFrame;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JPanel;

import javax.swing.JLabel;

import javax.swing.jspinner ;

import javax.swing.JSpinner.NumberEditor ;

import javax.swing.SpinnerNumberModel;

import javax.swing.SwingUtilities;

import javax.swing.SwingConstants ;

import javax.swing.event.ChangeListener ;

import javax.swing.event.ChangeEvent ;

import javax.swing.border.LineBorder ;

public class DateChooserJButton extends JButton {

private DateChooser dateChooser =null;

private String preLabel ="" ;

public DateChooserJButton() {

this(getNowDate()) ;

}

public DateChooserJButton(SimpleDateFormat df , String dateString) {

this() ;

setText(df,dateString) ;

}

public DateChooserJButton(Date date) {

this("",date);

}

public DateChooserJButton(String preLabel , Date date) {

if (preLabel!=null) this.preLabel = preLabel ;

setDate(date) ;

setBorder(null) ;

setCursor(new Cursor(Cursor.HAND_CURSOR)) ;

super.addActionListener( new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (dateChooser==null) dateChooser = new DateChooser();

Point p = getLocationOnScreen() ;

p.y = p.y+30 ;

dateChooser.showDateChooser(p) ;

}

}) ;

}

private static Date getNowDate() {

return Calendar.getInstance().getTime() ;

}

private static SimpleDateFormat getDefaultDateFormat() {

return new SimpleDateFormat("yyyy年MM月dd日HH时") ;

}

//覆盖父类的方法

public void setText(String s) {

Date date ;

try {

date = getDefaultDateFormat().parse(s) ;

}catch (ParseException e) {

date = getNowDate() ;

}

setDate(date) ;

}

public void setText(SimpleDateFormat df , String s) {

Date date ;

try {

date = df.parse(s) ;

}catch (ParseException e) {

date = getNowDate() ;

}

setDate(date) ;

}

public void setDate(Date date) {

super.setText(preLabel+getDefaultDateFormat().format(date));

}

public Date getDate() {

String dateString = getText().substring(preLabel.length());

try {

return getDefaultDateFormat().parse(dateString);

} catch (ParseException e) {

return getNowDate() ;

}

}

//覆盖父类的方法使之无效

public void addActionListener(ActionListener listener ) {

}

private class DateChooser extends JPanel implements ActionListener ,ChangeListener {

int startYear = 1980; //默认【最小】显示年份

int lastYear = 2050; //默认【最大】显示年份

int width = 200; //界面宽度

int height = 200; //界面高度

Color backGroundColor = Color.gray; //底色

//月历表格配色----------------//

Color palletTableColor = Color.white; //日历表底色

Color todayBackColor = Color.orange; //今天背景色

Color weekFontColor = Color.blue; //星期文字色

Color dateFontColor = Color.black; //日期文字色

Color weekendFontColor = Color.red; //周末文字色

//控制条配色------------------//

Color controlLineColor = Color.pink; //控制条底色

Color controlTextColor = Color.white; //控制条标签文字色

Color rbFontColor = Color.white; //RoundBox文字色

Color rbBorderColor = Color.red; //RoundBox边框色

Color rbButtonColor = Color.pink; //RoundBox按钮色

Color rbBTFontColor = Color.red; //RoundBox按钮文字色

JDialog dialog ;

JSpinner yearSpin ;

JSpinner monthSpin ;

JSpinner hourSpin ;

JButton[][] daysButton = new JButton[6][7] ;

DateChooser() {

setLayout(new BorderLayout());

setBorder(new LineBorder(backGroundColor, 2));

setBackground(backGroundColor);

JPanel topYearAndMonth = createYearAndMonthPanal();

add(topYearAndMonth,BorderLayout.NORTH);

JPanel centerWeekAndDay = createWeekAndDayPanal();

add(centerWeekAndDay,BorderLayout.CENTER);

}

private JPanel createYearAndMonthPanal(){

Calendar c = getCalendar() ;

int currentYear =c.get(Calendar.YEAR);

int currentMonth =c.get(Calendar.MONTH)+1;

int currentHour =c.get(Calendar.HOUR_OF_DAY);

JPanel result = new JPanel();

result.setLayout(new FlowLayout());

result.setBackground(controlLineColor);

yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,startYear,lastYear,1));

yearSpin.setPreferredSize(new Dimension(48,20)) ;

yearSpin.setName("Year") ;

yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####")) ;

yearSpin.addChangeListener(this) ;

result.add(yearSpin) ;

JLabel yearLabel = new JLabel("年");

yearLabel.setForeground(controlTextColor);

result.add(yearLabel);

monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth,1,12,1));

monthSpin.setPreferredSize(new Dimension(35,20)) ;

monthSpin.setName("Month") ;

monthSpin.addChangeListener(this) ;

result.add(monthSpin) ;

JLabel monthLabel = new JLabel("月");

monthLabel.setForeground(controlTextColor);

result.add(monthLabel);

hourSpin = new JSpinner(new SpinnerNumberModel(currentHour,0,23,1));

hourSpin.setPreferredSize(new Dimension(35,20)) ;

hourSpin.setName("Hour") ;

hourSpin.addChangeListener(this) ;

result.add(hourSpin) ;

JLabel hourLabel = new JLabel("时");

hourLabel.setForeground(controlTextColor);

result.add(hourLabel);

return result ;

}

private JPanel createWeekAndDayPanal() {

String colname[] = {"日","一","二","三","四","五","六"};

JPanel result = new JPanel();

//设置固定字体,以免调用环境改变影响界面美观

result.setFont(new Font("宋体", Font.PLAIN, 12));

result.setLayout(new GridLayout(7,7));

result.setBackground(Color.white);

JLabel cell ;

for(int i=0;i<7;i++) {

cell = new JLabel(colname[i]);

cell.setHorizontalAlignment(JLabel.RIGHT);

if (i==0 i==6) cell.setForeground(weekendFontColor) ;

else cell.setForeground(weekFontColor) ;

result.add(cell) ;

}

int actionCommandId = 0 ;

for(int i = 0; i < 6; i++)

for(int j = 0; j < 7; j++) {

JButton numberButton = new JButton();

numberButton.setBorder(null) ;

numberButton.setHorizontalAlignment(SwingConstants.RIGHT);

numberButton.setActionCommand(String.valueOf(actionCommandId)) ;

numberButton.addActionListener(this) ;

numberButton.setBackground(palletTableColor);

numberButton.setForeground(dateFontColor) ;

if (j==0 j==6) numberButton.setForeground(weekendFontColor) ;

else numberButton.setForeground(dateFontColor) ;

daysButton[i][j] = numberButton;

result.add(numberButton) ;

actionCommandId ++ ;

}

return result;

}

private JDialog createDialog(Frame owner ) {

JDialog result = new JDialog(owner,"日期时间选择",true) ;

result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);

result.getContentPane().add(this,BorderLayout.CENTER) ;

result.pack() ;

result.setSize(width, height);

return result ;

}

void showDateChooser(Point position ) {

Frame owner =(Frame)SwingUtilities.getWindowAncestor(DateChooserJButton.this) ;

if (dialog==null dialog.getOwner()!= owner) dialog = createDialog(owner ) ;

dialog.setLocation(getAppropriateLocation(owner ,position ) ) ;

flushWeekAndDay() ;

dialog.show();

}

Point getAppropriateLocation(Frame owner ,Point position ) {

Point result = new Point(position) ;

Point p = owner.getLocation() ;

int offsetX = (position.x+width) - (p.x + owner.getWidth() ) ;

int offsetY = (position.y+height) - (p.y + owner.getHeight() ) ;

if (offsetX >0 ) {

result.x -= offsetX ;

}

if (offsetY >0 ) {

result.y -= offsetY ;

}

return result ;

}

private Calendar getCalendar() {

Calendar result = Calendar.getInstance();

result.setTime(getDate()) ;

return result ;

}

private int getSelectedYear() {

return ((Integer)yearSpin.getValue()).intValue() ;

}

private int getSelectedMonth() {

return ((Integer)monthSpin.getValue()).intValue() ;

}

private int getSelectedHour() {

return ((Integer)hourSpin.getValue()).intValue() ;

}

private void dayColorUpdate(boolean isOldDay) {

Calendar c = getCalendar() ;

int day = c.get(Calendar.DAY_OF_MONTH);

c.set(Calendar.DAY_OF_MONTH,1);

int actionCommandId =day-2+c.get(Calendar.DAY_OF_WEEK) ;

int i = actionCommandId/7;

int j = actionCommandId%7;

if (isOldDay) daysButton[i][j].setForeground(dateFontColor) ;

else daysButton[i][j].setForeground(todayBackColor) ;

}

private void flushWeekAndDay() {

Calendar c = getCalendar() ;

c.set(Calendar.DAY_OF_MONTH,1);

int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);

int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK) ;

for(int i = 0; i < 6; i++) {

for(int j = 0; j < 7; j++) {

String s="" ;

if (dayNo>=1 && dayNo<=maxDayNo ) s = String.valueOf(dayNo) ;

daysButton[i][j].setText(s) ;

dayNo ++ ;

}

}

dayColorUpdate(false) ;

}

public void stateChanged(ChangeEvent e) {

JSpinner source =(JSpinner)e.getSource() ;

Calendar c = getCalendar() ;

if (source.getName().equals("Hour")) {

c.set(Calendar.HOUR_OF_DAY, getSelectedHour());

setDate(c.getTime());

return ;

}

dayColorUpdate(true) ;

if (source.getName().equals("Year"))

c.set(Calendar.YEAR, getSelectedYear());

else

// (source.getName().equals("Month"))

c.set(Calendar.MONTH, getSelectedMonth()-1);

setDate(c.getTime());

flushWeekAndDay() ;

}

public void actionPerformed(ActionEvent e) {

JButton source =(JButton)e.getSource() ;

if (source.getText().length()==0) return ;

dayColorUpdate(true) ;

source.setForeground(todayBackColor) ;

int newDay = Integer.parseInt(source.getText());

Calendar c = getCalendar() ;

c.set(Calendar.DAY_OF_MONTH,newDay);

setDate(c.getTime());

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有