Pablo Pablo - 1 month ago 15
Java Question

Disable dates JDates Chooser

I'm newbie and I want to disable dates like shown in this example but in a

JDateChooser
button. Here is my code and hope you guys can help me.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

RangeEvaluator evaluator = new RangeEvaluator();
evaluator.setStartDate(dateFormat.parse("2013-09-14"));
evaluator.setEndDate(dateFormat.parse("2013-09-23"));


JDateChooser calendar = new JDateChooser();
calendar.getCalendar.(evaluator);
// evaluator must be added to a JDayChooser object

calendar.setSize(180, 25);
calendar.setLocation(140, 640);
calendar.setVisible(true);
calendar.updateUI();
this.add(calendar);

Answer

Let's start with your question: How to add an IDateEvaluator to a JDateChooser? This is a really easy-to-solve problem but you must know the API first:

  • JDayChooser is a panel with buttons for each day of a month displayed in a tabular form.
  • JCalendar component has a JDayChooser embedded and adds the ability to change the year and month, updating the day chooser.
  • JDateChooser displays a JCalendar in a popup when you press the selector button.

So you basically need to get the reference to the JDayChooser component and add the date evaluator like this:

RangeEvaluator evaluator = new RangeEvaluator();
...
JDateChooser dataChooser = new JDateChooser();
dateChooser.getJCalendar().getDayChooser().addDateEvaluator(evaluator);

Other comments

  • Be aware of the buggy behavior described in this answer. You should set the current date explicitely after adding date evaluators to solve this issue.

  • You should never call any updateUI() method explicitely. It is intended to reset the UI property of a component to a value from the current Look and Feel.

  • Be aware that methods such as setSize(...), setLocation(...) or setBounds(...) are discouraged because Swing is not designed to be used with exact components size/location but with Layout Managers instead. See also this topic.

Comments