Swing自己沒有提供什麼華麗麗的日期時間選擇控件,因此筆者就在網上搜了個第三方的jar包jdatepicker-1.3.2.jar,基於此設計了個很輕量的日期選擇面板,很簡單的。效果圖以下所示:java
代碼以下:this
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextField; import net.sourceforge.jdatepicker.JDateComponentFactory; import net.sourceforge.jdatepicker.JDatePanel; import net.sourceforge.jdatepicker.impl.UtilDateModel; /** * Description:日期選擇面板窗口<br> * Copyright: Copyright (c) 2015<br> * Company: 河南電力科學研究院智能電網所<br> * @author shangbingbing 2015-01-01編寫 * @version 1.0 */ public class DialogDatePicker extends JDialog { private static final long serialVersionUID = 1L; /** * 彈出日期選擇窗口 * @param modal 是不是模態窗口 * @param txtSelectedDate 日期內容接收文本框 * @param screenX 顯示X點座標 * @param screenY 顯示Y點座標 */ public DialogDatePicker(boolean modal, final JTextField txtSelectedDate,int screenX,int screenY) { final JDatePanel jp = JDateComponentFactory.createJDatePanel(new UtilDateModel(new Date())); jp.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { if(txtSelectedDate != null) { try{ txtSelectedDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(jp.getModel().getValue())); } catch (Exception ex) { txtSelectedDate.setText(""); } } } }); JPanel pnl = (JPanel)jp; this.add(pnl); this.setTitle("選擇日期"); this.setResizable(false); this.setModal(modal); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.setBounds(screenX, screenY, 300, 300); this.setVisible(true); } public static void main(String[] args) { JTextField txtDate = new JTextField(); new DialogDatePicker(true,txtDate,300,400); System.out.println(txtDate.getText()); } }
【完】spa
做者:商兵兵設計
單位:河南省電力科學研究院智能電網所code
QQ:52190634orm