Java Swing basic example

This is the bare minimum that we need in order to have a Java Swing application up and running.

The code looks like this:

import javax.swing.*;

public class BasicFirstExample {

    public static void  main(String ... args){
        //Avoiding threading issues by invoking the frame through an anonymous
        //inner class via the static Swing Utilities method as follows
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Initialization the frame with a title as parameter
                //in the constructor
                JFrame myFirstFrame = new JFrame("Hello Frame World!");
                
                //Here comes the boilerplate code:
                
                //Setting the frame as visible. If it was not there
                //we wouldn't see the frame
                myFirstFrame.setVisible(true);
                //Setting the close-down of the application upon clicking the
                //close button in the swing frame. If it was not there, the JVM
                //would be holding on there even after closing down the swing through the button
                myFirstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                //Setting the size of the frame according to our needs. If this
                //wasn't there the default width is non-existant and the length barely visible
                //for a couple of chars of title
                myFirstFrame.setSize(200,100);
                //Setting the default position of the frame in the center of the screen.
                //If that wasn't there it will be initialized at the top left of the screen
                myFirstFrame.setLocationRelativeTo(null);
            }
        });
    }
}

Things to note:

  • We are first creating a JFrame instance call the constructor with a String as a parameter representing it’s title bar inscription.
  • We are are then calling setVisible(true) on the instance because surprisingly enough by default the visibility is set to false then non-visible.
  • We are then setting setDefaultCloseOperation() method because if we are not then after we close the little swing app from the close button the java application will still remain alive and running although counter-intuitive.
  • We are then setting setSize() because the default values are barely living any space for the title and almost non width space.
  • We are then calling setLocalisationRelativeTo() because otherwise our little Swing app will reside on the top left corner of our screen by default. Calling this method with null parameter will initialise it in the center of the screen.
  • All of the above are found in the body of an anonymous inner Runnable#run() call that is passed as a parameter inside the static SwingUtilities#invokeLater() method as per the suggestions of Sun in order for us not to run into unwanted exceptions following the rule of thumb of not setting state to components from within threads we are instantiating.

Performing a bit of housekeeping, namely including all the JFrame specific actions on a separate child class we could deduce the clutter inside the Runnable#run() method and extract it on the constructor of the child JFrame class. Besides all these actions we’ve seen (setting visibility, setting size, setting exit on close, setting relative position) are integral parts of the initialization of the frame and this makes total sense to include them within the constructor:

import javax.swing.*;

public class BasicFirstExample2 {

    public static void main(String ... args) {
         SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                 new MyFrame("Hello Frame World!");
             }
         });
    }

}

class MyFrame extends JFrame{

    MyFrame(String title) {
        super(title);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200,100);
        setLocationRelativeTo(null);
    }
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s