下拉框显示日期

 
   在开发dv后台,进行数据搜索时,需要根据评论的创建时间进行某个时间段的搜索,即搜索内容应是开始时间和结束时间的部分,所以我利用了标签来
   实现下拉框的显示,这样的重用性会更好一些。
1.把自定义的标签需要的配置文件放到指定的appfuse.tld文件内
 
  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>

   <tlib-version>1.0</tlib-version>
   <jsp-version>1.2</jsp-version>
   <short-name>appfuse</short-name>
   <description><![CDATA[Custom tag library for this application]]></description>

    <tag>
      <name>dateselect</name>
      <tag-class>com.ouou.webapp.taglib.DateTag</tag-class>
      <attribute>
         <name>name</name>
         <required>true</required>
         <rtexprvalue>true</rtexprvalue>
      </attribute>
      <attribute>
         <name>default</name>
         <required>true</required>
         <rtexprvalue>true</rtexprvalue>
      </attribute>
   </tag>

</taglib>

2.自定义标签
 
package com.ouou.webapp.taglib;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.time.FastDateFormat;
import org.displaytag.tags.el.ExpressionEvaluator;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.*;
import java.io.IOException;
import java.text.Collator;

import com.ouou.model.LabelValue;

/**
 * Created by IntelliJ IDEA.
 * User: houhy
 * Date: 2007-1-10
 * Time: 18:15:54
 * To change this template use File | Settings | File Templates.
 */
public class DateTag extends TagSupport {
    private static final long serialVersionUID = 3905548206810236097L;
    private String name;
    private String selected;
    protected final transient Log log = LogFactory.getLog(getClass());

    /**
     * @param name The name to set.
     *
     * @jsp.attribute required="false" rtexprvalue="true"
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @param selected The selected option.
     * @jsp.attribute required="false" rtexprvalue="true"
     */
    public void setDefault(String selected) {
        this.selected = selected;
    }

    /**
     * Process the start of this tag.
     *
     * @return int status
     *
     * @exception javax.servlet.jsp.JspException if a JSP exception has occurred
     *
     * @see javax.servlet.jsp.tagext.Tag#doStartTag()
     */
    public int doStartTag() throws JspException {
        ExpressionEvaluator eval = new ExpressionEvaluator(this, pageContext);

        if (null != selected && !"".equals(selected) && !"null".equals(selected)) {
            selected = eval.evalString("default", selected);
        } else {
            selected = getCurrDate();
        }

        String default_year = selected.substring(0,4);
        String default_month = selected.substring(5,7);
        String default_day = selected.substring(8,10);

        Locale userLocale = pageContext.getRequest().getLocale();
        List year  = this.buildYear(userLocale);
        List month = this.buildMonth(userLocale);
        List day   = this.buildDay(userLocale);

        StringBuffer sb = new StringBuffer();
        sb.append("<input name=/"").append(name).append("/" id=/"").append(name).append("/" type=/"hidden/" value=/"");
        sb.append(selected).append("/"/>/n");

        sb.append("<select name=/"").append(name).append("_month/" id=/"").append(name).append("_month/" class=/"select/">/n");
        for (Object option : month) {
            LabelValue curr_month = (LabelValue) option;
            sb.append("    <option value=/"").append(curr_month.getValue()).append("/"");

            if (default_month.equals(curr_month.getValue())) {
                sb.append(" selected=/"selected/"");
            }

            sb.append(">").append(curr_month.getLabel()).append("</option>/n");
        }
        sb.append("</select>");

        sb.append("<select name=/"").append(name).append("_day/" id=/"").append(name).append("_day/" class=/"select/">/n");
        for (Object option : day) {
            LabelValue curr_day = (LabelValue) option;
            sb.append("    <option value=/"").append(curr_day.getValue()).append("/"");

            if (default_day.equals(curr_day.getValue())) {
                sb.append(" selected=/"selected/"");
            }

            sb.append(">").append(curr_day.getLabel()).append("</option>/n");
        }
        sb.append("</select>");

        sb.append("<select name=/"").append(name).append("_year/" id=/"").append(name).append("_year/" class=/"select/">/n");
        for (Object option : year) {
            LabelValue curr_year = (LabelValue) option;
            sb.append("    <option value=/"").append(curr_year.getValue()).append("/"");

            if (default_year.equals(curr_year.getValue())) {
                sb.append(" selected=/"selected/"");
            }

            sb.append(">").append(curr_year.getLabel()).append("</option>/n");
        }
        sb.append("</select>");

        try {
            pageContext.getOut().write(sb.toString());
        } catch (IOException io) {
            throw new JspException(io);
        }

        return super.doStartTag();
    }

    /**
     * Release aquired resources to enable tag reusage.
     *
     * @see javax.servlet.jsp.tagext.Tag#release()
     */
    public void release() {
        super.release();
    }

    protected List buildYear(Locale locale) {
        String[] year = {"2006","2007","2008","2009","2010"};
        return buildOption(year,locale);
    }

    protected List buildMonth(Locale locale) {
        String[] month = {"01","02","03","04","05","06","07","08","09","10","11","12"};
        return buildOption(month,locale);
    }

    protected List buildDay(Locale locale) {
        String[] day = {"01","02","03","04","05","06","07","08","09","10",
                        "11","12","13","14","15","16","17","18","19","20",
                        "21","22","23","24","25","26","27","28","29","30","31"};
        return buildOption(day,locale);
    }

    protected List buildOption(String[] options,Locale locale) {
        List<LabelValue> buildList = new ArrayList<LabelValue>();
        try {
            for (String option : options) {
                if (!"".equals(option)) {
                    LabelValue optionLabel = new LabelValue(option,option);
                    if (!buildList.contains(optionLabel)) {
                        buildList.add(optionLabel);
                    }
                }
            }
            Collections.sort(buildList, new LabelValueComparator(locale));
            return buildList;
        }catch (NoSuchBeanDefinitionException n) {
            log.error(n);
            n.printStackTrace();
            return null;
        }
    }

    protected String getCurrDate() {
        Calendar calendar = Calendar.getInstance();
        return FastDateFormat.getInstance("yyyy-MM-dd").format(calendar.getTime());
    }

    /**
     * Class to compare LabelValues using their labels with
     * locale-sensitive behaviour.
     */
     public class LabelValueComparator implements Comparator {
        private Comparator c;

        /**
         * Creates a new LabelValueComparator object.
         *
         * @param locale The Locale used for localized String comparison.
         */
        public LabelValueComparator(Locale locale) {
            c = Collator.getInstance(locale);
        }

        /**
         * Compares the localized labels of two LabelValues.
         *
         * @param o1 The first LabelValue to compare.
         * @param o2 The second LabelValue to compare.
         *
         * @return The value returned by comparing the localized labels.
         */
        @SuppressWarnings("unchecked")
        public final int compare(Object o1, Object o2) {
            LabelValue lhs = (LabelValue) o1;
            LabelValue rhs = (LabelValue) o2;

            return c.compare(lhs.getLabel(), rhs.getLabel());
        }
    }
}

3.涉及到的LabelValue为:
 
package com.ouou.model;

import java.io.Serializable;
import java.util.Comparator;

/**
 * A simple JavaBean to represent label-value pairs. This is most commonly used
 * when constructing user interface elements which have a label to be displayed
 * to the user, and a corresponding value to be returned to the server. One
 * example is the <code>&lt;html:options&gt;</code> tag.
 * <p/>
 * <p/>
 * Note: this class has a natural ordering that is inconsistent with equals.
 * </p>
 *
 */
public class LabelValue implements Comparable, Serializable {
    private static final long serialVersionUID = 3689355407466181430L;

    /**
     * Comparator that can be used for a case insensitive sort of
     * <code>LabelValue</code> objects.
     */
    public static final Comparator CASE_INSENSITIVE_ORDER = new Comparator() {
        public int compare(Object o1, Object o2) {
            String label1 = ((LabelValue) o1).getLabel();
            String label2 = ((LabelValue) o2).getLabel();
            return label1.compareToIgnoreCase(label2);
        }
    };


    // ----------------------------------------------------------- Constructors


    /**
     * Default constructor.
     */
    public LabelValue() {
        super();
    }

    /**
     * Construct an instance with the supplied property values.
     *
     * @param label The label to be displayed to the user.
     * @param value The value to be returned to the server.
     */
    public LabelValue(String label, String value) {
        this.label = label;
        this.value = value;
    }


    // ------------------------------------------------------------- Properties


    /**
     * The property which supplies the option label visible to the end user.
     */
    private String label = null;

    public String getLabel() {
        return this.label;
    }

    public void setLabel(String label) {
        this.label = label;
    }


    /**
     * The property which supplies the value returned to the server.
     */
    private String value = null;

    public String getValue() {
        return this.value;
    }

    public void setValue(String value) {
        this.value = value;
    }


    // --------------------------------------------------------- Public Methods

    /**
     * Compare LabelValueBeans based on the label, because that's the human
     * viewable part of the object.
     *
     * @see Comparable
     */
    public int compareTo(Object o) {
        // Implicitly tests for the correct type, throwing
        // ClassCastException as required by interface
        String otherLabel = ((LabelValue) o).getLabel();

        return this.getLabel().compareTo(otherLabel);
    }

    /**
     * Return a string representation of this object.
     */
    public String toString() {
        StringBuffer sb = new StringBuffer("LabelValue[");
        sb.append(this.label);
        sb.append(", ");
        sb.append(this.value);
        sb.append("]");
        return (sb.toString());
    }

    /**
     * LabelValueBeans are equal if their values are both null or equal.
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }

        if (!(obj instanceof LabelValue)) {
            return false;
        }

        LabelValue bean = (LabelValue) obj;
        int nil = (this.getValue() == null) ? 1 : 0;
        nil += (bean.getValue() == null) ? 1 : 0;

        if (nil == 2) {
            return true;
        } else if (nil == 1) {
            return false;
        } else {
            return this.getValue().equals(bean.getValue());
        }

    }

    /**
     * The hash code is based on the object's value.
     *
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return (this.getValue() == null) ? 17 : this.getValue().hashCode();
    }
}
4.jsp测试创建的按钮


<%@ include file="/common/taglibs.jsp"%>

<%
    String beg = (String)request.getAttribute("beg");
    String end =(String)request.getAttribute("end");
    try{
 String k=request.getParameter("key");
 k = java.net.URLEncoder.encode(k,"utf-8");
 request.setAttribute("k",k);
  }catch(Exception e){}
%>
<c:set var="searchButton">
 <form method="post"  name="videoSearch"  action="/comment/video/list.html?type=<c:out value="${videocommentsList.type}"/>&s=1" onSubmit="javascript:return checkCommentDate();"  <c:if test="${videocommentsList.s!= 1}">style="display:none"</c:if>>
         <fmt:message key="search.begin.time"/>:
         <appfuse:dateselect name="beg" default="<%=beg%>"/>
         <fmt:message key="search.end.time"/>:
         <appfuse:dateselect name="end" default="<%=end%>"/>
        <fmt:message key="comments.keywords"/>:<input type="text" style="margin-right: 5px"
         name="key" value="<c:out value="${videocommentsList.key}"/>"/>
         <fmt:message key="groupcomments.UserId"/>:<input type="text" style="margin-right: 5px"
         name="user" value="<c:out value="${videocommentsList.user}"/>"/>
        <input type="submit" name="submit" style="margin-right: 5px"
         value="<fmt:message key="button.search"/>"/>
   </form>
</c:set>
<p>
<c:out value="${searchButton}" escapeXml="false" />
</p>
<display:column titleKey="comments.operate" style="width: 20%"  escapeXml="false" sortable="false" media="html" >
        <input type="button" style="margin-right: 5px"
        οnclick="javascript:if(window.confirm('Are you sure'))location.href='<c:url value="/comment/video/list.html?commentId=${vcList.commentId}&type=${videocommentsList.type}&beg=${videocommentsList.beg}&end=${videocommentsList.end}&key=${k}&user=${videocommentsList.user}&s=${videocommentsList.s}&p=${videocommentsList.p}&method=del"/>'"
        value="<fmt:message key="button.delete"/>"/>
        //此时的k值根据传递页面间传递的值进行取值,可保证每次操作后显示的内容为操作前所输入的值
        <c:choose>
        <c:when test="${vcList.status == '0'}">
        <input type="button" style="margin-right: 5px"
        οnclick="javascript:if(window.confirm('Are you sure'))location.href='<c:url value="/comment/video/list.html?commentId=${vcList.commentId}&type=${videocommentsList.type}&beg=${videocommentsList.beg}&end=${videocommentsList.end}&key=${k}&user=${videocommentsList.user}&s=${videocommentsList.s}&p=${videocommentsList.p}&method=cha"/>'"
        value="<fmt:message key="button.audited"/>"/>
        </c:when></c:choose>
    </display:column>

此时,下拉框的年,月,日的名字对应为beg_year,beg_month,beg_day,end_day.......

5.第四步使用到的标签文件的引用内容
<%@ page import="org.springframework.context.ApplicationContext"%>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@ page language="java" errorPage="/error.jsp" pageEncoding="UTF-8" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://acegisecurity.org/authz" prefix="authz" %>
<%@ taglib uri="http://www.springmodules.org/tags/commons-validator" prefix="v" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
<%@ taglib uri="http://struts-menu.sf.net/tag-el" prefix="menu" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://www.opensymphony.com/oscache" prefix="cache" %>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/page" prefix="page"%>
<%@ taglib uri="/WEB-INF/appfuse.tld" prefix="appfuse" %>
<%
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
%>
6.判断时间符合实际情况

 function checkCommentDate(){
    var begindate=document.videoSearch.beg_year.options[document.videoSearch.beg_year.selectedIndex].text+"-"+document.videoSearch.beg_month.options[document.videoSearch.beg_month.selectedIndex].text+"-"+document.videoSearch.beg_day.options[document.videoSearch.beg_day.selectedIndex].text;
 var enddate=document.videoSearch.end_year.options[document.videoSearch.end_year.selectedIndex].text+"-"+document.videoSearch.end_month.options[document.videoSearch.end_month.selectedIndex].text+"-"+document.videoSearch.end_day.options[document.videoSearch.end_day.selectedIndex].text;
    if(!checkDate(begindate,"/u5f00/u59cb/u65f6/u95f4")){//开始时间
  return false;
    }
 if(!checkDate(enddate,"/u7ed3/u675f/u65f6/u95f4")){//结束时间
  return false;
    }
 document.videoSearch.beg.value=begindate;//把开始时间付给当前的beg的值,此时下拉框显示的是变化后的时间
 document.videoSearch.end.value=enddate;
    return true;

  }
 
  function checkDate(theVal,fieldname){
    var filter = /^((((1[6-9]|[2-9]/d)/d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]/d|3[01]))|(((1[6-9]|[2-9]/d)/d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]/d|30))|(((1[6-9]|[2-9]/d)/d{2})-0?2-(0?[1-9]|1/d|2[0-8]))|(((1[6-9]|[2-9]/d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;
    if (filter.test(theVal)){
        return true;
    }else{
        alert("请输入一个合法的" + fieldname +"!");
        return false;
    }
  }
7.判断开始时间小于结束时间:
   function beforDate(){
  var begindate=document.videoSearch.beg_year.options[document.videoSearch.beg_year.selectedIndex].text+"/"+document.videoSearch.beg_month.options[document.videoSearch.beg_month.selectedIndex].text+"/"+document.videoSearch.beg_day.options[document.videoSearch.beg_day.selectedIndex].text;
  var enddate=document.videoSearch.end_year.options[document.videoSearch.end_year.selectedIndex].text+"/"+document.videoSearch.end_month.options[document.videoSearch.end_month.selectedIndex].text+"/"+document.videoSearch.end_day.options[document.videoSearch.end_day.selectedIndex].text;
     if(Date.parse(new Date(begindate))<=Date.parse(new Date(enddate))){
  return true;
    }
 else
 {
  return false;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用JComboBox来创建下拉框,然后根据选择的日期更新日历显示。 下面是一个简单的实现,可以根据需要进行修改和优化: ```java import java.awt.*; import java.awt.event.*; import java.time.*; import java.time.format.*; import javax.swing.*; public class CalendarGUI extends JFrame implements ActionListener { private final JComboBox<String> yearBox, monthBox; private final JLabel[] dayLabels; private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-M-d"); public CalendarGUI() { setTitle("Calendar"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); JPanel topPanel = new JPanel(); topPanel.add(new JLabel("Year:")); yearBox = new JComboBox<>(); for (int year = LocalDate.now().getYear() - 10; year <= LocalDate.now().getYear() + 10; year++) { yearBox.addItem(String.valueOf(year)); } yearBox.setSelectedItem(String.valueOf(LocalDate.now().getYear())); yearBox.addActionListener(this); topPanel.add(yearBox); topPanel.add(new JLabel("Month:")); monthBox = new JComboBox<>(); for (int month = 1; month <= 12; month++) { monthBox.addItem(String.valueOf(month)); } monthBox.setSelectedItem(String.valueOf(LocalDate.now().getMonthValue())); monthBox.addActionListener(this); topPanel.add(monthBox); add(topPanel, BorderLayout.NORTH); JPanel centerPanel = new JPanel(new GridLayout(7, 7)); String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; for (String weekDay : weekDays) { centerPanel.add(new JLabel(weekDay, SwingConstants.CENTER)); } dayLabels = new JLabel[42]; for (int i = 0; i < dayLabels.length; i++) { dayLabels[i] = new JLabel("", SwingConstants.CENTER); centerPanel.add(dayLabels[i]); } updateCalendar(); add(centerPanel, BorderLayout.CENTER); pack(); setLocationRelativeTo(null); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == yearBox || e.getSource() == monthBox) { updateCalendar(); } } private void updateCalendar() { int year = Integer.parseInt((String) yearBox.getSelectedItem()); int month = Integer.parseInt((String) monthBox.getSelectedItem()); LocalDate date = LocalDate.of(year, month, 1); int firstDayOfWeek = date.getDayOfWeek().getValue() % 7; int lastDay = date.plusMonths(1).minusDays(1).getDayOfMonth(); for (int i = 0; i < dayLabels.length; i++) { if (i < firstDayOfWeek || i >= firstDayOfWeek + lastDay) { dayLabels[i].setText(""); } else { dayLabels[i].setText(String.valueOf(i - firstDayOfWeek + 1)); } } } public static void main(String[] args) { SwingUtilities.invokeLater(CalendarGUI::new); } } ``` 这个GUI界面包含一个顶部面板和一个中心面板。顶部面板包含两个下拉框,用于选择年份和月份;中心面板包含一个网格布局,用于显示日历。网格布局中第一行为星期几的标签,接下来是42个用于显示日期的标签(最多有6*7=42天)。当用户选择年份或月份时,通过计算更新中心面板中的日期标签。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值