gpt4 book ai didi

java - 对日历SET中的日期添加一些条件

转载 作者:行者123 更新时间:2023-12-02 01:31:14 25 4
gpt4 key购买 nike

如何在 SWT 中为我的日历添加一些条件?例如设置日期在1970年到2030年之间,日历中不允许显示超过这个范围的日期。

最佳答案

您没有内部方法来执行此操作。因此,您可以有一些条件来检查选择日期是否在最小日期和最大日期之间,并且可以抛出如下所示的错误弹出窗口,并且可以将选择重置为任何日期。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

/**
* The Class RestrictYearInCalender.
*
* @author subash
*/
public class RestrictYearInCalender {

/** The min date. */
private static Date minDate;

/** The max date. */
private static Date maxDate;

/** The format. */
private static SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Calender");
shell.setLayout(new RowLayout());

Calendar cal = Calendar.getInstance();

/* Set the minimum */
cal.set(1970, 0, 0);
minDate = cal.getTime();

/* Set the maximum */
cal.set(2030, 0, 0);
maxDate = cal.getTime();

DateTime calendar = new DateTime(shell, SWT.CALENDAR);
calendar.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
/* Get the selection from the calender drop down*/
int day = calendar.getDay();
int month = calendar.getMonth() + 1;
int year = calendar.getYear();

/* Parse the selection */
Date newDate = null;
try
{
newDate = format.parse(day + "/" + month + "/" + year);
}
catch (ParseException e)
{
return;
}

/* Compare it to the minimum and maximum */
if(newDate.after(maxDate) || newDate.before(minDate))
{
/* Set to the maximum or maximum according to requirement*/
Calendar cal = Calendar.getInstance();
cal.setTime(minDate);
calendar.setMonth(cal.get(Calendar.MONTH));
calendar.setDay(cal.get(Calendar.DAY_OF_MONTH));
calendar.setYear(cal.get(Calendar.YEAR));
MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Range selection should be between 1970-2030");
}
}
});

shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

Calender Error dialog

关于java - 对日历SET中的日期添加一些条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com