A Monthly Calendar in Java Swing that Ends at a Given Date

In this blog post we will build a monthly calendar in Java Swing using the scheduler library. We will use the monthly view of the calendar but we will make it render only 3 months after the current month. By default there are no limits how far users can scroll the months in Single month view both back- and forth-wards. We will let our users scroll as many months they want in the past but only scroll 3 months ahead.

Continue reading

Custom Painting of Resources in Java Scheduler

In this blog post we will explain how to color cells and resources in the Resource view of the calendar based on a certain criteria. In our case we take the “Resource Table” sample from the Samples for the Java Swing Scheduler and we will edit its code to color the header and background of cells that correspond to given resources, in our sample it is an employee:

We will also add tooltips that show when the mouse is over cells that correspond to this employee:

Continue reading

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.

Binding the Java Planner to Microsoft SQL Server Using JDBC

In this blog post we will bind to an MS SQL database called bookings. There we will select all data from a table named booking_data. The data is DateTime values. We will use the values to change the background of corresponding calendar cells in a simple Java application. The Java application renders a single-month calendar built with MindFusion Scheduler for Java library.

I. MS SQL EXPRESS Server Configuration

We download and install MS SQL EXPRESS server from https://www.microsoft.com/en-us/sql-server/sql-server-downloads. The installation also includes an application called “Sql Server Configuration Manager”. We start that application and click on the “SQL Services” tab. There we need to make sure that two services are running:

  • SQL Server
  • SQL Server Browser

You start these services by pressing the arrows in the toolbar at the top. If you cannot do this you need to change the Start Mode for this service. Double click it and in the Properties dialog that appears click on the “Service” tab. There you will find the “Start Mode” property and change it to “Manual”. Once you’ve done this you can start, stop or pause the service from the toolbar icons.

SQL Server Config Manager: Services

In order to start an SQL Server Service you might have to change its Start Mode to “Manual”.

Then we click on the “SQL Native Client” node and we select the “Client Protocols” tab. We make sure the TCP/IP Protocol is enabled.

SQL Server Config Manager: Enable TCP/IP

Make sure the TCP/IP protocol is enabled for the JDBC connection to succeed

The next step is to download Microsoft SQL Server Management Studio from https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017

Once we install it and start it we can create a new database called bookings. We right click on the Databases menu and choose “New Database”. We call it “bookings”. Then we expand the tree under “bookings” and right click on the “Tables” node. A window opens where we can define the columns for our new table. We add two columns:

  • id of type integer, which we set at primary key by right-clicking on it.
  • booked_date of type DateTime which will hold the dates that are booked.
Create a new table using MS SQL Server Management Studio

MS SQL Server management Studio: the dialog for defining a new table

After we are done we choose save and at this point we can provide a name for our table. We call it booking_data. With the table defined we right-click on it and choose “Edit Top 200 Rows”. There we add just three days (Jan 16th, Jan 22nd, Jan 26th) all of which in the current month. The data is auto-saved.

MS SQL Server management Studio: Table Edit

MS SQL Server Management Studio: here is how you edit the table data

The next step is to create a new user that will connect to this database. We click the “Security” node on the navigation tree and then “Logins”. Right-click and we choose “New Login”. In the dialog that opens we provide username and password. In order to do that we need to have the Login method set to “SQL Server authentication”. In the next tab “Server Roles” the new user must have “public” role. Then in “User Mapping” we tick the “bookings” database. In the Securables tab in the “Grant” grant column for the user we tick the “Connect SQL” permission. Then we close the dialog.

Grant SQL Connect to a DB User

Grant the new user the right to perform an SQL connection.

We get back to the bookings database and right-click on it. We choose “Properties” and from the dialog we click on the “Permissions” menu. There we select the user we’ve just created and in the Grant column of the underlying table we grant her the “Select” permission.

Granting User Permissions

Grant the DB user ‘Select’ permission to perform the required SQL query

With that the setup of our server and user is ready.

II. JDBC Driver & MS SQL Express Connection Properties

We download Microsoft’s JDBC Driver for MS SQL Server from this link: https://docs.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server?view=sql-server-2017 and extract it. Next we create a new Java project. For this project we’ve used IntelliJ IDEA but any other Java IDE will do. In the project tree to the right we create a subfolder that we call “libs”. There we copy the jar of JDBC driver from the folder where we extracted it. Microsoft provides two versions of the driver depending on the JRE that you use. In our case we choose the version for JRE 10, which is called mssql-jdbc-7.0.0.jre10.jar. Next we right-click on the name of our project and select “Open Module Properties”. In the dialog we choose the “Modules” menu and there we click on the “Dependencies” tab and select the mssql-jdbc-7.0.0.jre10.jar module.

Configuring IntelliJ Project Modules

Configuring the IntelliJ Project to include the JDBC driver module

We click on the src folder of the project and add a new class, which we call MainWindow.java. In it we write the method establishConnection. This method is responsible for connecting to the MS SQL database “bookings”. Here is the code that makes the connection:

private void establishConnection() throws ClassNotFoundException
{

Connection conn = null;
PreparedStatement pst;

try {
// db parameters
String sql = "SELECT booked_date FROM booking_data";

String userName = "mindfusion";
String password = "mf123";

String url = "jdbc:sqlserver://DESKTOP-NV9S0TU\\SQLEXPRESS;databaseName=bookings;";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);

pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();

If you’ve followed strictly the steps we’ve outlined so far at this point you would successfully connect to your MS SQL Server with the credentials you’ve set up following the guide so far.

III. The Schedule Application

We download MindFusion Java Swing Scheduler from https://mindfusion.eu/java-scheduler.html and unzip it. We copy JPlanner.jar in the libs folder of the project and add it as a project dependency from the “Open Module Settings” menu. Then we define a Calendar variable and assign it to a new instance of the Calendar class.

public MainWindow() throws ClassNotFoundException
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(368, 362);
setTitle("MindFusion.Scheduling Sample: Minimal Application");

calendar = new Calendar();
calendar.setTheme(ThemeType.Light);
..................
..................
..................

establishConnection();
}

private Calendar calendar;

At the end of the method we call establishConnection and connect to the MS SQL Server.

IV. Styling the Calendar Dates

The aim of our sample application shall be to color those cells of the calendar that correspond to the dates we’ve read from the database. In order to do this we use the DateStyle class that sets some useful appearance properties to a range of cells that are specified with the setFrom and setTo methods. We use setBrush to change the background of the cell.

while (rs.next()) {
System.out.println(rs.getString("booked_date"));
Date date = rs.getDate("booked_date");

DateStyle dStyle = new DateStyle();
dStyle.setFrom(new DateTime(date));
dStyle.setTo(new DateTime(date));
Style style = new Style();
style.setBrush(new SolidBrush(Color.pink));
dStyle.setStyle(style);

calendar.getDayStyles().add(dStyle);

}

Finally we add the style to the DayStyles collection of the calendar.

Here is the final application:

Scheduling application in Java Swing with MS SQL Server JDBC Connection

MindFusion Java Swing application with the Scheduling library and MS SQL Server

You can download the project together with the MS SQL Server JDBC driver library and the scheduling library from this link:

Download JPlanner Sample Application That Uses MS SQL Server JDBC Connection

About MindFusion Scheduling for Java Swing: The library provides extensive feature-set for creating and customizing all sorts of calendars, task lists, time-management tables, resource allocation tables and other. It boasts various options for customizing appearance and numerous events for handling user actions. The distribution archive includes a lot of samples and extensive documentation. Learn more at https://mindfusion.eu/java-scheduler.html