Java Swings/First Examples

On this page, we'll get started with swing. We'll look at the classes  and , and build a basic swing "hello world" application.

JFrames
JFrames are swing components. A swing component is a part of a graphic user interface (GUI). Frames, windows, text boxes, buttons, switches and many other parts of a GUI application are all components. The root class of all swing components is the  class, and other swing components, including , are subclasses of. is an abstract class, so it cannot be instantiated directly, but can be subclassed, which is useful if you want to write your own custom GUI component.

A JFrame is a top-level component, meaning that it contains other components, but is not contained itself. It's onscreen appearance is dictated by the platform, but generally it is a window that the user can resize, move, maximize, minimize, and has its own title bar.

Probably the best way to get familiar with a, as well as components in general, is to run a short example program that creates one. The following program will do the trick.

The code creates an empty JFrame. When you run it, you should see a window appear on your screen. The code also illustrates some methods that can be used with JFrames, some of which are commented out. I would encourage you to experiment a bit with commenting and uncommenting these, and seeing the effect.

JLabels
An empty frame is only so exciting, so for this section, we're going to look at JLabels, and put one in a JFrame. A  is a GUI component that can hold an image, some text, or both.

The following code creates a GUI version of the "Hello World!" application.

This program is pretty much like the previous one, except that it creates a  with the text "Hello, World!" in addition to the, and uses the     method to add it to the frame before making it visible. If you compile and run the program as-is, the "Hello, world" text will be aligned on the left side of the window.

By uncommenting the line  you can move the text to the center.

Summary
We've seen how to create a JFrame, a top level container for a swing GUI application, as well as a few  methods that can be used to change its settings. We also looked at the  class, and used the  's   method to add a   to the frame in order to create a simple application.

Looking at these examples, you might be wondering what other methods exist for JFrames, JLabels, and other components. Although we'll continue to look at more components and more methods. Fortunately, Oracle provides an invaluable online reference to all of the core Java classes, including swing, which can be viewed at the following link:

http://docs.oracle.com/javase/7/docs/api/index.html

Java/JFrame