Testing our Environment – part 3

Navigate to the Application Class code and open

Figure 4 Application Class template code
Figure 4 Application Class template code

Next extend the main method with the following code:

EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println("The start of our application.");

And add at the top an import statement for the EventQueue

import java.awt.EventQueue;

So what we finally have looks like this:

Figure 5 Finished application code
Figure 5 Finished application code

You may be looking at this code and asking yourself why are we running this on the Event Dispatch Thread. Well, we do not need to do this for this simple program, not least because we are not using any GUI/Swing objects. But as we are going to use this as a template to build the rest of the application and the application most definitely will use Swing and GUI objects we will start as we mean to go on.So why are we using the Event Dispatch Thread?

There are lots of opinions and comments around Java, Swing, Multi Threading and poor performance. The prevailing mindset suggests that when using objects that are not thread safe you should access these on the Event Dispatch thread. As Swing objects are not thread safe they need to be accessed on the Event Dispatch Thread.

In practical terms Java programs should execute intensive time consuming activities in a separate thread to allow the rest of the program to remain responsive. What we are aiming to do here is ensure all the input events that the program needs to process will continue to be processed even if the application is busy managing data. We are all familiar with the situation where our program stops responding to mouse and keyboard and appears to freeze, then after a while it catches up and suddenly all the clicks and key presses are processed. This is an example of what we are trying to avoid.

When we run this it will write ‘The start of our application.’ to the default out device.
So save the file and then let’s run this within Eclipse and then as a standalone application.
To save you can use the menu bar and select ‘File-Save’ or a quicker more convenient method is to press and hold the ‘Ctrl’ key and then press the ‘S’ key.

click here to download the java source code

Testing our Environment – part 3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s