Java Swing is a standard in Java 2 (Java 1.2). If you are using Java 1.2 or later, then Java Swing package is available for use. If you have Java 1.1, then you a separate Java Swing package can be downloaded and added.
Java Swing Components

The Java Swing toolkit includes a rich array of components: from basic components, such as buttons and check boxes, to rich and complex components, such as tables and text. Even deceptively simple components, such as text fields, offer sophisticated functionality, such as formatted text input or password field behavior. These components are commonly referred as Java Swing components.

Now I will give brief description of commonly used Java Swing components followed by Java Swing example.

Java Swing Labels

JLabel is a display area for a short text string or an image, or both. A label does not react to input events. As a result, it cannot get the keyboard focus. A label can, however, display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it.

A JLabel object can display either text, an image, or both. You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

You can also specify the position of the text relative to the image. By default, text is on the trailing edge of the image, with the text and image vertically aligned.

A label's leading and trailing edge are determined from the value of its ComponentOrientation property. At present, the default ComponentOrientation setting maps the leading edge to left and the trailing edge to right.

Finally, you can use the setIconTextGap method to specify how many pixels should appear between the text and the image. The default is 4 pixels.

The Java Swing example below demonstrates use of Jlabel. It creates a window which shows different alignments of JLabel. Seven different labels are created and are added to container. Label1 is a simple label. Label 2, 3, 4, 5, 6 has different alignments such as LEFT, CENTER, RIGHT etc. For Label7 Text added with setText().

Java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JLabelDemo extends JApplet {
	/* Declaration */
	private Container Panel;

	private LayoutManager Layout;

	private JLabel Label1;
	private JLabel Label2;
	private JLabel Label3;
	private JLabel Label4;
	private JLabel Label5;
	private JLabel Label6;
	private JLabel Label7;

	public JLabelDemo() {
		/* Instantiation */
		Layout = new GridLayout(7, 1);
		Label1 = new JLabel("A Simple Label");
		Label2 = new JLabel("A Label with LEFT alignment", JLabel.LEFT);
		Label3 = new JLabel("A Label with CENTER alignment", JLabel.CENTER);
		Label4 = new JLabel("A Label with RIGHT alignment", JLabel.RIGHT);
		Label5 = new JLabel("A Label with LEADING alignment", JLabel.LEADING);
		Label6 = new JLabel("A Label with TRAILING alignment", JLabel.TRAILING);
		Label7 = new JLabel();
		Panel = getContentPane();

		/* Location */
		Panel.setLayout(Layout);
		Panel.add(Label1);
		Panel.add(Label2);
		Panel.add(Label3);
		Panel.add(Label4);
		Panel.add(Label5);
		Panel.add(Label6);
		Panel.add(Label7);

		/* Decoration */
		Panel.setBackground(Color.yellow);
		Label7.setHorizontalAlignment(JLabel.CENTER);
		Label7.setForeground(Color.blue);
		Label7.setText("Text added with setText");
	}

}


Java Swing Buttons

JButtons are just as you'd think, buttons on the screen that a user can press to change properties of your program. A JButton can be instantiated and used in a GUI just like a java.awt.Button. Buttons can be configured, and to some degree controlled, by Actions. Using an Action with a button has many benefits beyond directly configuring a button.

A Swing button can display both text and an image. The underlined letter in each button's text shows the mnemonic the keyboard alternative for each button. When a button is disabled, the look and feel automatically generates the button's disabled appearance. However, you could provide an image to be substituted for the normal image.

How you implement event handling depends on the type of button you use and how you use it. Generally, you implement an action listener, which is notified every time the user clicks the button.

The following Java Swing example demonstrates how to create JButton. It creates a simple JButton with string, ’This is a JButton’.

Java Code:
import java.awt.*;
import javax.swing.*;

public class JButtonDemo {

	public static void main(String[] a) {
		JFrame f = new JFrame("JButton Demo");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JButton b = new JButton("This is a JButton");
		f.getContentPane().add(b);
		f.pack();      
		f.setVisible(true);
        }
}


Java Swing Combo Boxes

The JComboBox is a very handy drop-down menu control that lets you select one option from a list of things. The JComboBox is component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.

Combo boxes require little screen space, and their editable text field form is useful for letting the user quickly choose a value without limiting the user to the displayed values. Combo boxes can be more appropriate when space is limited or more than a few choices are available.

A JComboBox can have two very different forms, the default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it. The user can type a value in the text field or click the button to display a drop-down list.

The combo box fires an action event when the user selects an item from the combo box's menu. Combo boxes also generate item events, which are fired when any of the items' selection state changes.

The following Java Swing example demonstrates the use of JcomboBox. It creates two combo boxes, the uneditable combo box and the editable combo box.

Java Code:
import javax.swing.*;

class ComboPanel extends JPanel {

	String choices[] = {
			"Mercury", "Venus", "Earth", 
			"Mars", "Jupiter", "Saturn", 
			"Uranus","Neptune", "Pluto"};

	public ComboPanel() {

		JComboBox combo1 = new JComboBox();
		JComboBox combo2 = new JComboBox();

		for (int i=0;i<choices.length;i++) {
			combo1.addItem (choices[i]);
			combo2.addItem (choices[i]);
		}

		combo2.setEditable(true);
		combo2.setSelectedItem("X");
		combo2.setMaximumRowCount(4);
		add(combo1);
		add(combo2);
	}
}

public class JComboboxDemo {

	public static void main(String args[]){

		JFrame frame = new JFrame("JCombobox Demo");

		frame.add(new ComboPanel());
		frame.setSize(200, 200);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}


Java Swing Check Boxes

A check box is an item that can be selected or deselected, and which displays its state to the user. By convention, any number of check boxes in a group can be selected.

The JCheckBox class provides support for check box buttons. The JCheckbox is a control that lets you select more than one attribute at a time on the screen by 'checking' i.e. ticking selections in a list. This is useful when multiple choices are involved, for example the people you want to play in your football team. Each CheckBox has a state of either selected or deselected.

Using the JCheckBoxMenuItem class you can also put check boxes in menus. As JCheckBox and JCheckBoxMenuItem are inherited from AbstractButton, Swing check boxes have all the usual button characteristics. For example, you can specify images to be used in check boxes.

Check boxes are similar to radio buttons, but their selection model is different. User can select any number of check boxes in a group: none, some, or all can be selected. A group of radio buttons can have only one button selected.

A check box generates one item event and one action event per click. Generaly, you listen only for item events, as they let you determine whether the click selected or deselected the check box.

This following Java Swing example illustrates you how to create a Check Box component in Java Swing. It creates a simple Swing check box with string, 'This is the JCheckBox'.

Java Code:
import javax.swing.*;

public class JCheckboxDemo {
	public static void main(String[] args){
		JFrame frame = new JFrame("JCheck Box Demo");
		JCheckBox chk = new JCheckBox("This is the JCheckBox");
		frame.add(chk);
		frame.setSize(200, 200);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}


Java Swing - Making Dialogs

JDialog is the main class in swing for creating a dialog window. You can use this class to create a custom dialog, or invoke the many class methods in JOptionPane to create a variety of standard dialogs.

The JDialog component contains a JRootPane as its only child. The contentPane should be the parent of any children of the JDialog. As a convenience add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write:

Java Code:
       dialog.add(child);
And the child will be added to the contentPane. The contentPane is always non-null. Attempting to set it to null generates an exception. The default contentPane has a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JDialog.

In a multi-screen environment, you can create a JDialog on a different screen device than its owner.

The Java Swing example below demonstrates use of simple Jdialog. After executing the code a dialog window opens with question Yes or No. If you answer yes it returns 0 and if you answer No it returns 1 which can be seen in the console.

Java Code:
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class JDialogDemo {

	public static void main(String argv[]) {

		JOptionPane pane = new JOptionPane("Yes or NO?");
		Object[] options = new String[] { "Yes", "No" };
		pane.setOptions(options);
		JDialog dialog = pane.createDialog(new JFrame(), "JDilaog demo");
		dialog.setVisible(true);
		Object obj = pane.getValue();
		int result = -1;

		for (int k = 0; k < options.length; k++)
			if (options[k].equals(obj))
				result = k;

		System.out.println("Your choice: " + result);
	}
}


Java Swing Event Handling

The Java Swing event model is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.

Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.

The most important rule to keep in mind about event listeners is that they should execute very quickly. Because all drawing and event-listening methods are executed in the same thread, a slow event-listener method can make the program seem unresponsive and slow to repaint itself. If you need to perform some lengthy operation as the result of an event, do it by starting up another thread (or somehow sending a request to another thread) to perform the operation.

Every event-listener method has a single argument an object that inherits from the EventObject class. Although the argument always descends from EventObject, its type is generally specified more precisely. For example, the argument for methods that handle mouse events is an instance of MouseEvent, where MouseEvent is an indirect subclass of EventObject.

Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible.

To help you avoid implementing empty method bodies, the API generally includes an adapter class for each listener interface with more than one method. For example, the MouseAdapter class implements the MouseListener interface. An adapter class implements empty versions of all its interface's methods.

Inner classes can also be useful for event listeners that implement one or more interfaces directly. You can create an inner class without specifying a name this is known as an anonymous inner class.

An EventHandler class supports dynamic generation of simple, one-statement event listeners. Probably the most common use of EventHandler is to extract a property value from the source of the event object and set this value as the value of a property of the target object.

The example below demonstrates event handling for a swing component named Slide bar. This program gives you two slide bar and a image inside the frame. When you drag the horizontal slide bar then the image will be increased or decreased from left and right according to the value of the slide bar while when you drag the vertical slide bar then the image will be increased or creased from top and bottom according to the value of the slide bar.

Java Code:
import javax.swing. *;
import javax.swing.event.*;
import java.awt.*;

public class SwingEventHandling{
	public static void main(String[] args) {
		final JSlider width = new JSlider(JSlider.HORIZONTAL, 5, 150, 125);
		final JSlider height = new JSlider(JSlider.VERTICAL, 5, 150, 125);

		class DynamicIcon implements Icon {
			public int getIconWidth() {
				return width.getValue();
			}

			public int getIconHeight(){
				return height.getValue();
			}

			public void paintIcon(Component c, Graphics g, int x, int y) {
				g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);
			}
		}

		Icon icon = new DynamicIcon();
		final JLabel jl = new JLabel(icon);

		class Updater implements ChangeListener {
			public void stateChanged(ChangeEvent e) {
				jl.repaint();
			}
		};

		Updater ud = new Updater();
		width.addChangeListener(ud);
		height.addChangeListener(ud);
		JFrame fm = new JFrame();
		fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container ca = fm.getContentPane();
		ca.setLayout(new BorderLayout());
		ca.add(width, BorderLayout.NORTH);
		ca.add(height, BorderLayout.WEST);
		ca.add(jl, BorderLayout.CENTER);
		fm.setSize(250,250);
		fm.setVisible(true);
	}
}


Using Panels

JPanel is a generic lightweight container. The JPanel class provides general-purpose containers for lightweight components. By default, panels don't paint anything except for their background; however, you can easily add borders to them and otherwise customize their painting.

In the simplest case, you use a JPanel exactly the same way as you would a Panel. Allocate it, drop components in it, then add the JPanel to some Container. However, JPanel also acts as a replacement for Canvas (there is no JCanvas). When using JPanel as a drawing area in lieu of a Canvas, there are two additional steps you usually need to follow. First, you should set the preferred size via setPreferredSize(). Secondly, you should use paintComponent for drawing, not paint. And since double-buffering is turned on by default, the first thing you normally do in paintComponent is clear the off-screen bitmap via super.paintComponent.

By default, panels are opaque. This makes them work well as content panes, and can help painting efficiency. You can make a panel transparent by invoking setOpaque(false). A transparent panel draws no background, so that any components underneath show through.


The following Java Swing example demonstrates use of JPanel. It creates a JPanel with GridBagLayout. A label 'Hello' is added to this panel. Border of the panel is set to color black with function setBorder(). When you click on the button, 'Change label text' in the window, it changes label text from 'Hello' to 'Hello World'.

Java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class JPanelDemo {

	public void buildGUI() {

		final JLabel label = new JLabel("Hello", JLabel.CENTER);
		label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		JPanel p = new JPanel(new GridBagLayout());
		p.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		p.setPreferredSize(new Dimension(100, 100));
		p.add(label, new GridBagConstraints());
		JButton btn = new JButton("Change label text");
		JFrame f = new JFrame();
		f.getContentPane().add(p, BorderLayout.CENTER);
		f.getContentPane().add(btn, BorderLayout.SOUTH);
		f.pack();
		f.setLocationRelativeTo(null);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);

		btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				label.setText("Hello World");
			}
		});
	}

	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new JPanelDemo().buildGUI();
			}
		});
	}
}

Using Menus

Swing menu components are subclasses of JComponent. Consequently, they have all the benefits of a Swing component, and you can treat them as such with respect to layout managers and containers.

These are some notable features of the Swing menu system:

  • Icons can augment or replace menu items.
  • Menu items can be radio buttons.
  • Keyboard accelerators can be assigned to menu items; these appear next to the menu item text.
  • Most standard Swing components can be used as menu items.


Swing provides familiar menu separators, checkbox menu items, pop-up menus, and submenus for use in your applications. In addition, Swing menus support keyboard accelerators and "underline" style (mnemonic) shortcuts, and you can attach menu bars to the top of Swing frames with a single function that adjusts the frame insets accordingly.

Swing menu items can be highlighted when the mouse pointer passes over them, they can be clicked to indicate that the user has made a choice, they can be disabled and grayed like buttons, and they can be assigned action commands to assist with event handling.

The Java Swing example below demonstrates the use of JMenu. It creates three menus File, Edit, Color. File menu consists of menu item 'Quit', Edit menu consists of menu item 'Erase'. Color menu consists of menu items with different colors. You can select color and color of the window will change. If you select menu item Erase, it will erase color. Menu item 'quit' will exit the application.

Java Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MenuExample extends JFrame {

	public MenuExample() {

		//set the Frame size
		this.setSize(400, 400);

		//Create the menu bar.
		JMenuBar menuBar = new JMenuBar();

		//Build the first menu.
		JMenu filemenu = new JMenu("File");
		JMenu editmenu = new JMenu("Edit");
		JMenu colormenu = new JMenu("Color");

		//add the submenu's to the menu bar (File, Edit, Color)
		menuBar.add(filemenu);
		menuBar.add(editmenu);
		menuBar.add(colormenu);

		//start creating the menu items.
		JMenuItem quititem = new JMenuItem("Quit");
		/* for each menu item add an ActionListener:when a user chooses
		 this menu item the actionPerformed function will be called. 
		 Since an ActionListener is being created the required 
		 function actionPerformed(ActionEvent e) must be declared.
		 In this case we don't need the actionEvent that occured
		 because we only need to change the background color 
		 of the frame
		 */
		quititem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(-1);
			}
		});

		//do the same for all the menu items.
		JMenuItem eraseitem = new JMenuItem("Erase");
		eraseitem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().setBackground(Color.white);
			}
		});
		JMenuItem reditem = new JMenuItem("Red");
		reditem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().setBackground(Color.red);
			}
		});
		JMenuItem greenitem = new JMenuItem("Green");
		greenitem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().setBackground(Color.green);
			}
		});
		JMenuItem blueitem = new JMenuItem("Blue");
		blueitem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().setBackground(Color.blue);
			}
		});
		JMenuItem pinkitem = new JMenuItem("Pink");
		pinkitem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().setBackground(Color.pink);
			}
		});
		JMenuItem blackitem = new JMenuItem("Black");
		blackitem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().setBackground(Color.black);
			}
		});

		//add the sub menu items to their respective menus
		filemenu.add(quititem);
		editmenu.add(eraseitem);
		colormenu.add(reditem);
		colormenu.add(greenitem);
		colormenu.add(blueitem);
		colormenu.add(pinkitem);
		colormenu.add(blackitem);

		//exit the program when the user clicks on the X in the window
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//start the background as white.
		this.getContentPane().setBackground(Color.white);
		this.setJMenuBar(menuBar); //set the Frames JMenuBar
		this.setTitle("Menu Example"); //title of the frame
		this.setVisible(true); //show the Frame
	}

	public static void main(String[] args) {
		new MenuExample();
	}
}