JAVA界面添加时间控件

前言

本控件依赖datepicker.jar包,只能获取时间,不能通过代码设置时间
1.通过初始化代码重新设置时间(Date = new Date(2000,1,1))
2.使用JXDatePicker,缺点:缺少时分秒,具体可参考这里

下载

下载datepicker.jar
链接: https://pan.baidu.com/s/1f1OjpfO0ceyEPUVorDMgzQ 提取码: w79w

代码

private static Calendar c=Calendar.getInstance();//通过calendar去获取具体时间
private static DatePicker dateTimeStart;

//初始化
String DefaultFormat = "yyyy-MM-dd HH:mm:ss";//如果设置成yyyy-MM-dd则获取年月日
Date date = new Date();
Font font = new Font("Times New Roman", Font.BOLD, 14);//字体、大小
Dimension dimension = new Dimension(177, 24);//控件大小
dateTimeStart = new DatePicker(date, DefaultFormat, font, dimension);
dateTimeStart.setBounds(266, 83, 121, 21);
dateTimeStart.setLocale(Locale.CHINA);
dateTimeStart.setTimePanleVisible(true);
panel.add(dateTimeStart);//面板中加入控件

//获取年月日时分秒具体值
c.setTime((Date)dateTimeStart.getValue());
struCond.struStartTime.dwYear = c.get(c.YEAR);
struCond.struStartTime.dwMonth = c.get(c.MONTH)+1;
struCond.struStartTime.dwDay = c.get(c.DAY_OF_MONTH);
struCond.struStartTime.dwHour = c.get(c.HOUR_OF_DAY);
struCond.struStartTime.dwMinute = c.get(c.MINUTE);
struCond.struStartTime.dwSecond = c.get(c.SECOND);

//通过初始化设置时间
int year = 1900;
int month = 1;
int day =  1;
String DefaultFormat = "yyyy-MM-dd";
Date date = new Date(year, month, day);
Font font = new Font("Times New Roman", Font.BOLD, 14);
Dimension dimension = new Dimension(177, 24);
contentPane.remove(dTPStartDate);//删除原控件
dTPStartDate = new DatePicker(date, DefaultFormat, font, dimension);
dTPStartDate.setBounds(157, 120, 149, 21);
dTPStartDate.setLocale(Locale.CHINA);
dTPStartDate.setTimePanleVisible(true);
contentPane.add(dTPStartDate);//添加新控件
contentPane.validate();//重新调整panel布局,不可缺少该句

参考

https://blog.csdn.net/baidu_35085676/article/details/72903756

你可能感兴趣的:(Java)