The Different Ways to Style a Schedule

In this blog post we will look at the different levels of sty‌ling the elements and items of a schedule made with a MindFusion scheduling library. In our sample we use the Java Scheduling Library, but the API members that we use and the cascading levels of styling a schedule are universal across all MindFusion Scheduling components.

I. Top Level: Theme

At the top level of styling you have themes. The scheduling library has a set of predefined themes: Light, Lila, Silver, Standard, Vista, Windows2013. You apply one of the predefined themes this way:

calendar.setTheme(ThemeType.Vista);

Here is what the calendar looks like styled with the vista theme:

In JavaScript, the themes are defined in CSS styles and you must reference the desired file and set the name of the theme to the calendar instance. In the other libraries, they are built-in and usually are available as members of an enum.

You have the option to create a custom theme, which you can save and apply this way:

calendar.setCustomTheme(new MyTheme());

Another way to apply the custom theme in Java Scheduling is:

calendar.setCustomTheme(new MyTheme());

Here is the look of the calendar with the custom theme:

The custom theme has changed some of the colors, widened the header so that the week days could be seen and set some borders on the cells.

Creating a custom Theme requires that you override a strict set of methods. They are the public members of the Theme class. You should override all of them. Among the methods that style the calendar for each view – getMonthRangeSettings getMonthSettings etc. You could override in detail only the method that is responsible for styling the view you would use – if it is only one. For the rest of the methods you could just write:

private void initialize_MyTheme_ListViewSettings()
{
	_listViewSettings = super.createListViewSettings();
}

Every method in the Theme class must be dutifully implemented and all settings set. That comes from the fact that a Theme is the last and topmost styling instrument and it must know how to style any element that might not be explicitly styled down the tree.

The online and offline documentations of the Java Scheduling library come with topics that list in details the styling settings for each of the predefined themes. Our advice is that you get the code of the Theme that looks closest to what you want to have as a structure and modify it.

The sample project that you can download at the bottom of this post implements a custom Theme based on the Vista theme and lists all members in a theme that you must set with all details.

II. View and Item Settings

One level down the tree are the view settings properties. They are available for any view. You can access those settings with the getMonthSettings getMonthRangeSettings etc. methods. Each one of those methods returns the styling settings of a particular view. You should use the one that corresponds to the view you’ve chosen:

//set the view to SingleMonth
calendar.setCurrentView(CalendarView.SingleMonth);
//get the styling settings for SingleMonth view
calendar.getMonthSettings().getDaySettings().setTodayFillColor(Color.green);

You can style the items, regardless of the view used, with the ItemSettings object:

calendar.getItemSettings().setPadding(20);

The *Settings properties define the appearance of items in terms of alignment, spacing, padding, shadow, date format. The coloring of the elements is left to Style instances. Thus, if you want to change the color of items, you will use:

//customize just the items through the itemSettings field
calendar.getItemSettings().setPadding(20);
		
Style itemStyle = new Style();
itemStyle.setBrush(new SolidBrush(Color.white));
itemStyle.setHeaderTextColor(Color.DARK_GRAY);		
itemStyle.setHeaderTextShadowStyle(ShadowStyle.None);
calendar.getItemSettings().setStyle(itemStyle);

This styles all items on the calendar. For styling a particular item, you should use on of the methods listed underneath.

Our calendar now has green header on the current day, the background of events is white and there is a bit of a padding added to the events.

III. Using Events to Style Particular Items

When you want to select items that you want to style based on some distinct characteristics, you can use events. In our sample we handle the itemCreated event, where we check if the start date of an appointment happens to be during the weekend:

// Listen for item creation and for draw events
calendar.addCalendarListener(new CalendarAdapter(){
	//apply custom styling to selected items
	public void itemCreated(ItemEvent e) {
		onItemCreated(e);
	}				
});

The Java Scheduler provides various events, which are accessible through a CalendarListener and CalendarAdapter instances. We handle the itemCreated event this way:

//color in red events that are scheduled to start on weekends
protected void onItemCreated(ItemEvent e) {

	Item item = e.getItem();
	if(item.getStartTime().getDayOfWeek() == DayOfWeek.Saturday || 
		item.getStartTime().getDayOfWeek() == DayOfWeek.Sunday)
		{
			item.getStyle().setBrush(new SolidBrush(new Color(213, 28, 32)));
			item.getStyle().setHeaderTextColor(Colors.White);
			item.getPointedStyle().setBrush(new SolidBrush(new Color(100, 100, 100)));
		}	
}

The ItemEvent class provides the item that was created and you can use the instance to apply any particular styling to the item.

Here is our scheduler, which now colors the items on weekends in red:

In JavaScript, the items have a special field that allows you to assign to them a custom CSS style that you’ve defined. The style will be applied to the particular item only. The field is called ‘cssClass’.

IV. Custom Drawing

When you need to style in a very unique way calendar elements and nothing else helps, you have the option to draw them the way you want. Custom drawing can be made for many parts of the calendar. The available elements are identified as members of the CustomDrawElements enumeration.

You tell the control that you want to use custom drawing this way:

//specify that we will use custom drawing	
calendar.setCustomDraw(EnumSet.of(CustomDrawElements.CellContents));

The custom drawing must be part of the draw method, which is also a member of CalendarListener:

// Listen for item creation and for draw events
calendar.addCalendarListener(new CalendarAdapter(){
				
			
//add custom drawing to CellContents
@Override()
public void draw(CalendarDrawEvent e) {
	onDraw(e);
	} 
			
});

The event handler method looks like this:

//apply custom drawing to selected items
private void onDraw(CalendarDrawEvent e)
{
	if (e.getElement() == CustomDrawElements.CellContents)
	{
		DateTime date = e.getDate();		
		
		//color in light yellow the background of the first 10 days of a month
		if (date.getDay() < 11)
		{
			// Do the custom drawing
			Rectangle2D bounds = new Rectangle2D.Double(
			e.getBounds().getX(), e.getBounds().getY(),
			e.getBounds().getWidth() - 1, e.getBounds().getHeight() - 1);
			new AwtGraphics(e.getGraphics()).fillRectangle(Brushes.LightYellow, bounds);
		}
	}
}

The Calendar’s drawEvent class gives us useful methods to learn more about the item that is being drawn. In our case we want to draw the cell contents, so we check if draw was called for the cell contents, and if yes, we get the bounds of the element. We need the check, because draw is called for all elements that support custom drawing and we need to identify which one is drawn at the moment.

Thanks to the custom drawing, the monthly schedule now has a light yellow background on the first ten days of the month:

With this our review of the methods to style a schedule is finished. You can download the complete source code of the sample together with all MindFusion libraries used from this link:

How to Style a Java Schedule: Download Project Source Code

You can post questions about Mindusion Scheduling components at MindFusion online forums.

About MindFusion Scheduling Components MindFusion Scheduling components are available for a variety of platforms for web, mobile and desktop programming. All of them include a robust feature set that includes 6 calendar views, predefined themes, various events, predefined forms for creating appointments and recurrence. The components are fully interactive, easy to customize and style and are the ideal choice for any application that needs to implement time management features. You can learn more about MindFusion Scheduling tools at https://mindfusion.eu/scheduling-pack.html.

A Monthly Calendar in Java With Events and Recurring Appointments

This is a step-by-step guide that teaches you how to:

  • Setup the MindFusion Scheduler for Java library to display a single
    month calendar.
  • Attach and handle an event when the user clicks a calendar cell.
  • Create and setup recurrent events/appointments.
  • Perform custom drawing on a specific cell.

The sample builds a monthly calendar, which responds to a user click on a calendar cell by creating a recurrent appointment. The appointment is repeated on each subsequent day of the week for unlimited number of months.

When the user selects a given calendar cell (the 6th day of the month), a special icon appears. The icon is rendered using custom drawing.

Note: In this tutorial we use the words “appointment” and “event” interchangeably. Let’s start:

1. How to Setup the Calendar

All packages of the calendar are included in a single *.jar file – JPlanner.jar In our sample we will reference the following packages:

import com.mindfusion.common.*;
import com.mindfusion.common.Rectangle;
import com.mindfusion.drawing.*;
import com.mindfusion.drawing.awt.AwtImage;
import com.mindfusion.scheduling.*;
import com.mindfusion.scheduling.awt.*;
import com.mindfusion.scheduling.model.*;

For detailed reference about the packages and the classes of the schedule library check the online help.

Here are the first settings for our schedule:

  calendar = new AwtCalendar();
  calendar.beginInit();
  //set the current time
  calendar.setCurrentTime(DateTime.now());
  DateTime today = DateTime.today();
  //set the current date
  calendar.setDate(today);
  // Select the current date
  calendar.getSelection().set(DateTime.today());

We create a new calendar and signal that initialization starts. The time and date shown at the application start are the current date and time. We also select the cell with the current date.

Let’s make the calendar show exactly one month:

calendar.setCurrentView(CalendarView.SingleMonth);

By default each cell in a single month view has its header size set to 0, which makes the current date show in the center of the cell. As a consequence any events in the cell won’t have space to be rendered.

Java Scheduler: the header takes all the cell's height

Java Scheduler: the header takes all the cell’s height

Since we plan to create appointments on user click, we must push the header to the top and free cell space for drawing the events. This is very easy to do, just set:

calendar.getMonthSettings().getDaySettings().setHeaderSize(20);

Now the header is 20 px. and the rest will be for our appointments.

Java Scheduler: the header is 20px.

Java Scheduler: the header is 20px.

For now we are ready initializing the calendar.

calendar.endInit();

2. Handling User Clicks.

User clicks are handled with the dateClick event. We need an instance of the CalendarAdapter and there we associate the dateClick event with a method – onDateClicked. The event is fired when a date is selected.

 calendar.addCalendarListener(new CalendarAdapter(){
            public void dateClick(ResourceDateEvent e) {
                onDateClicked(e);
            }

        });

3. Create an Appointment and a Recurrence.

The first part of our event handler method is:

protected void onDateClicked(ResourceDateEvent e) {

    int dayIndex = e.getDate().getDayOfWeek();

    Appointment item = new Appointment();
    item.setStartTime(e.getDate());
    item.setEndTime(e.getDate());
    item.setHeaderText(events[dayIndex]);
    item.getStyle().setBrush(brushes[dayIndex]);

Here we create an Appointment and set its start and end date to the date which was clicked. The ResourceDateEvent keeps data about the date, the resource, if any and other useful information. The header text is the text, which will be rendered at the appointment. The style object contains appearance data for the cell and we use the setBrush
method to change the background of the appointment.

The second part of the method creates the Recurrence object:

      recurrence = new Recurrence();
      recurrence.setPattern(RecurrencePattern.Weekly);
      recurrence.setDaysOfWeek(getDayOfWeek(dayIndex));
      recurrence.setStartDate(e.getDate());
      recurrence.setRecurrenceEnd(RecurrenceEnd.Never);
      item.setRecurrence(recurrence);

The recurrence is once a week. There’s additional work to be done when we set the day of the week with setDaysOfWeek. The method accepts as an argument one of the DaysOfWeek enumeration values and we have to convert the index of the day to such value.

private int getDayOfWeek ( int i ) {

        switch (i) {
            case 1:
                return DaysOfWeek.Monday;
            case 2:
                return DaysOfWeek.Tuesday;
            case 3:
                return DaysOfWeek.Wednesday;
            case 4:
                return DaysOfWeek.Thursday;
            case 5:
                return DaysOfWeek.Friday;
            case 6:
                return DaysOfWeek.Saturday;
        }

        return DaysOfWeek.Sunday;

    }

Finally, let’s add the item with the recurrence pattern to the schedule items collection:

 calendar.getSchedule().getItems().add(item);

4. Custom Drawing a Cell’s Header

The last thing that needs to be done is to draw the icon on the special 6th day of each month. We will perform item drawing and we add to the calendar initialization code this line:

 calendar.setCustomDraw(CustomDrawElements.CalendarItem);

Now we are ready to handle the draw event:

   //add a listener for custom draw
       calendar.addCalendarListener(new CalendarAdapter()
        {
            @Override()
            public void draw(DrawEvent e) {
                onDraw(e);
            }
        });

Below is the first part of the handler method:

 private void onDraw(DrawEvent e)
    {
 if(e.getDate().getDay() == 6 )
            {
                java.awt.Image img = null;

                try {
                    // Read the image file from an input stream
                    InputStream is = new BufferedInputStream(
                            new FileInputStream("../cake.png"));
                    img = ImageIO.read(is);

                } catch (IOException ioe) {
                }

Here we read an image from an InputStream. The calendar method for drawing images requires mindfusion.scheduling.AwtImage and we must convert the java image:

AwtImage awtImage = new AwtImage(img);

Then we get the bounds of the drawing area and render the image:

   //gets the bounds of the drawing area
    Rectangle r = e.getBounds();
             
   //draw the image
   e.getGraphics().drawImage(awtImage, e.getBounds().getLeft(), e.getBounds().getTop(), 32, 32);

 }

The image is 32 x 32 pixels and gets clipped in the appointment.

Java Scheduler: the appointment's height is not enough.

Java Scheduler: the appointment’s height is not enough.

We’ll have to resize the item header to give it more space:

calendar.getItemSettings().setSize(32);

And now everything works just fine:

MindFusion Java Calendar: Month View with Events

MindFusion Java Calendar: Month View with Events

The sample is available for download from here:

Monthly Calendar in Java with Recurrent Appointments and Events

About Scheduling for Java Swing: A programming class library written entirely in Java that lets you build the most sophisticated schedules, calendars and task managers fast and easy. The component boasts a comprehensive feature set that includes custom-typed events, undo/redo functionality, scrolling, tool tips and much more. You can choose among six view styles, which are easy to change and customize. The appearance of each schedule is completely customizable and supports themes, user-assigned mouse cursors and a variety of font, pen and brush options.

A detailed list with the features of the tool is available at the Scheduling for Java Swing features page. The trial version includes a variety of samples and you have plenty of sample code to study. Online documentation with useful tutorials is also available.

The library is royalty-free, source-code is also available. You can see a list of the current prices here. Check the discount page for a list of the available discounts.

Diagramming for Java Swing, V4.1.4 Released

MindFusion is happy to announce the new version of the Java Diagramming library. The release offers useful new features and improvements.

What’s New in Version 4.1.4

Resize table columns and rows

Columns and rows of a TableNode can now be resized interactively if its AllowResizeColumns or AllowResizeRows properties are enabled. In order to resize, move the mouse pointer to the border line on column’s right side or row’s bottom side until it shows resize cursor and start dragging. The control raises tableColumnResizing and tableRowResizing events to let you validate new size or prevent resizing some elements. The tableColumnResized and tableRowResized events are raised after the operation completes.

Java Diagram Library: Table Nodes

Java Diagram Library: Table Nodes

License keys

There is no separate trial build of the control’s JAR archive provided anymore. Instead, call the setLicenseKey method of DiagramView to disable the component’s evaluation mode and stop displaying trial messages. setLicenseKey > is static and you can call it just once before creating any views. License key strings are now listed on the Keys & Downloads page at MindFusion’s customer portal.

Miscellaneous

  • Undo/redo records for in-place edit operations are now created automatically.
  • KeepInsideDiagram constraint prevents a node from leaving diagram boundaries during user interaction (the older RestrictItemsToBounds property does not stop nodes from leaving diagram area but returns them to original position if dropped outside).
  • Dashed selection frames are now drawn in two colors and should be visible on both the default white background and custom darker backgrounds. You can change the second dash color via DashBackground property of HandlesVisualStyle.
  • Improved mouse capture for composite controls hosted inside ControlNodes.
  • StartPoint and EndPoint properties provide a shortcut to setting the first and last control points of a DiagramLink.

Fixed bugs

  • Fixed text clipping problem when magnifier is over TreeViewNode.
  • Links to contained nodes were left visibly disconnected from them after deleting a folded ContainerNode.
  • Lasso selection could not select strictly horizontal or vertical straight-line links when IncludeItemsIfIntersect is disabled.

The trial version is available for download from the following link:

Download MindFusion.Diagramming for Java Swing, V4.1.4 Trial Version

Technical support
MindFusion puts special effort in providing high quality technical support to all its clients and evaluators. You can post your questions about Diagramming for Java or any other of our components at the forum, help desk or at support@mindfusion.eu. All support inquiries are usually answered within hours of being received.

About Diagramming for Java Swing: MindFusion.Diagramming for Java Swing provides your Java application with all necessary functionality to create and customize a diagram. The library is very easy to integrate and program. There are numerous utility methods, rich event set, more than 100 predefined shapes. The tool supports a variety of ways to render or export the diagram, advanced node types like TreeView nodes, hierarchical nodes, tables, container nodes and many more. There are 15 automatic layouts, various input / output options and fully customizable appearance. A detailed list with JDiagram’s features is uploaded here. You can check the online demo to see some of the functionality implemented.

Diagramming for Java Swing is royalty free, there are no distribution fees. Licenses depend on the count of developers using the tool – check here the prices.

Diagramming for Java Swing, V4.1.2

MindFusion is proud to announce the new release of the Java diagramming library with the following new features:

AnchorPatern improvements

  • You can use the XUnit and YUnit properties to specify the coordinates of an AnchorPoint as a fixed offset from the node’s top-left corner rather than in percentage, so that the point position does not change when the node is resized.
  • The AnchorPattern property of Shape class lets you associate anchor points with shape definitions. If a ShapeNode instance does not contain its own AnchorPattern, it will derive the one defined by the node’s Shape.
Anchor points for a box shape.

Anchor points for a box shape.

Miscellaneous

  • Type of Margin property of LinkLabel has been changed from float to Thickness.
    ~ The changeUnit method sets a new MeasureUnit and scales the coordinates of diagram items to keep them the same size.
  • Fixed node spacing in bottom-to-top TreeLayout.
  • TabbedScrollPane allows reordering tabs when AllowTabReorder property is enabled.
  • Improved quality of print preview page images.
  • DisableTextClipping property added to PdfExporter enables work-around for limit-check errors when Adobe Reader prints to some PostScript printers.
The tree layout is used to arrange the newly created boxes dynamically.

The tree layout is used to arrange the newly created boxes dynamically.

The trial version is available for download from the following link:

Download MindFusion.Diagramming for Java Swing, V4.1.2 Trial Version

Technical support
MindFusion puts special effort in providing high quality technical support to all its clients and evaluators. You can post your questions about Diagramming for Java or any other of our components at the forum, help desk or at support@mindfusion.eu. All support inquiries are usually answered within hours of being received.

About Diagramming for Java Swing: MindFusion.Diagramming for Java Swing provides your Java application with all necessary functionality to create and customize a diagram. The library is very easy to integrate and program. There are numerous utility methods, rich event set, more than 100 predefined shapes. The tool supports a variety of ways to render or export the diagram, advanced node types like TreeView nodes, hierarchical nodes, tables, container nodes and many more. There are 15 automatic layouts, various input / output options and fully customizable appearance. A detailed list with JDiagram’s features is uploaded here. You can check the online demo to see some of the functionality implemented.

Diagramming for Java Swing is royalty free, there are no distribution fees. Licenses depend on the count of developers using the tool – check here the prices.

Diagramming for Java Swing, V4.1.1

MindFusion has released a new version of its Diagramming component for Java. It contains a few new features as well improvements of existing ones. Here are details:

Improved arrowhead rendering

  • arrowheads are rendered as a single path when possible and several arrowhead Shape definitions have been changed to implement mitered joints when HeadPen is set to a thick pen.
  • the point where end segments connect to arrowheads can be specified via the Shape.LinkSegmentInset property. Shape definitions from the ArrowHeads class set it to suitable default value. This allows using transparent or semi-transparent brushes without seeing the link line drawn behind arrowheads.
  • arrowhead shadows are no longer filled if the link’s EffectiveBrush is null or fully transparent.
  • IntermediateShape is now also rendered for Bezier links.
New vs. old arrowheads rendering

New vs. old arrowheads rendering

Miscellaneous

  • Set the LinkLabel.Brush property to fill the background of link labels.
  • Multiple-resize of rotated nodes fixed to apply same offsets in nodes’ local coordinate system.
  • Fixed a bug where setting the CaptionBackBrush property of containers would hide the caption-bar borders.
  • Java 8 update 20 fix from this patch now included in released version.
Labels at links

Labels at links

The trial version is available for download from the following link:

Download MindFusion.Diagramming for Java Swing, V4.1.1 Trial Version

Technical support
MindFusion puts special effort in providing high quality technical support to all its clients and evaluators. You can post your questions about Diagramming for Java or any other of our components at the forum, help desk or at support@mindfusion.eu. All support inquiries are usually answered within hours of being received.

About Diagramming for Java Swing: MindFusion.Diagramming for Java Swing provides your Java application with all necessary functionality to create and customize a diagram. The library is very easy to integrate and program. There are numerous utility methods, rich event set, more than 100 predefined shapes. The tool supports a variety of ways to render or export the diagram, advanced node types like TreeView nodes, hierarchical nodes, tables, container nodes and many more. There are 15 automatic layouts, various input / output options and fully customizable appearance. A detailed list with JDiagram’s features is uploaded here. You can check the online demo to see some of the functionality implemented.

Diagramming for Java Swing is royalty free, there are no distribution fees. Licenses depend on the count of developers using the tool – check here the prices.