You are on page 1of 34

All rights reserved.

Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is prohibited.

Java ReferencePoint Suite


SkillSoft Corporation. (c) 2002. Copying Prohibited.

Reprinted for Balaji Nallathambi, Verizon Balaji@verizon.com Reprinted with permission as a subscription benefit of Books24x7, http://www.books24x7.com/

Table of Contents
Point 5: Creating GUI with Swing....................................................................................................1 Swing Programming .........................................................................................................................2 Swing Components.................................................................................................................2 Using Swing Packages...........................................................................................................2 Basic Swing Programming..............................................................................................................4 Adding a Tool Tip and an Image Icon to a Button ...................................................................4 Adding Borders to Swing Components...................................................................................5 Creating a Text Area Containing a Scroll Bar.........................................................................8 Creating a Password Field......................................................................................................9 Creating a List Box Control...................................................................................................10 Creating a Combo Box Component......................................................................................13 Creating a Check Box Component.......................................................................................14 Creating a Toggle Button......................................................................................................16 Creating a Radio Button ........................................................................................................16 Creating a Slider Bar............................................................................................................17 . Advanced Swing Programming .....................................................................................................19 Layout Managers..................................................................................................................19 Creating a Tabbed Pane.......................................................................................................22 Creating Menus and Sub Menus..........................................................................................24 Creating a Tree Component.................................................................................................25 Creating a Table Component................................................................................................28 UserValidation Feature.......................................................................................................29 Using Threads in a Swing Application.........................................................................................31

Point 5: Creating GUI with Swing


Deepak Pandya Java" Foundation Class (JFC) is a development kit that simplifies the task of creating components, such as menus, labels, and buttons. You use JFC components to create graphicbased applets and applications. The Swing package is part of JFC and is integrated into version 1.2 of Java. This ReferencePoint introduces you to the fundamentals of creating Graphical User Interface (GUI) applications by using Swing components, such as trees, tabbed panes, images, and tool tips. These components are flexible and have varied features. For example, you can create a button in various shapes for an applet, add an icon or image to the button, or change the border of the button.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Swing Programming
To use Swing components, include the javax.swing package in the Java program. This package provides a set of classes to manage user interface components such as trees and panes. All classes in the javax.swing package are derived from the JComponent class, which in turn, is derived from the java.awt.Container class. All these classes are container classes. The hierarchy of swing classes is shown in Figure 251. A container class has a pane that is used as a container for all components. You can access this pane by using the getContentPane() method. Every Swing program contains at least one toplevel Swing container, such as JWindow, JFrame, JPane, and JApplet. The toplevel Swing container provides support for the Swing components.

Figure 251: Class Hierarchy in Swing

Swing Components
The most commonly used Swing components are: JFrame: A toplevel container for all Swing components such as labels and buttons. JPanel: A container that enables you to position the Swing components. JButton and JLabel: Components that are selfsufficient entities inside a container.

Note The Swing components are JavaBeans and can be used in other applications in various environments.

Using Swing Packages


You use swing packages to create Swing components. Table 251 describes the various Swing packages: Table 251: The Swing Packages Swing Packages Javax.swing.border Javax.swing.colorchooser Javax.swing.event Javax.swing.filechooser Javax.swing.plaf Javax.swing.table Javax.swing.text
Reprinted for v697039, Verizon

Description Enables you to create borders around components. Enables you to display a color chart and choose a color. Enables you to manage events in eventdriven programming. Enables you to provide File selection dialog boxes in an application. Provides Pluggable Look and Feel (PLAF) capability. Enables you to display and manipulate the data in a table.
SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

Javax.swing.html Javax.swing.tree

Enables you to create and manipulate singleline or multiple line textentry fields. Allows you to display Swing applications in the HTML format. Allows you to create and manipulate a tree view of data.

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Basic Swing Programming


Listing 251 shows how to create a frame by using Swing programming: Listing 251: A Swing Program
import javax.swing.*; public class Hello { public static void main(String[] args) { JFrame frame=new JFrame ("SwingProgram"); JLabel label=new JLabel ("I swing "); frame.getContentPane().add(label); frame.setVisible(true); } }

This code imports the main swing package by using the statement:
import javax.swing.*.

The execution of the program starts from the main() method. An object of the JFrame class is declared by passing the title of the frame, SwingProgram, as its parameter. An object of the JLabel class is declared with the caption, I swing. The frame container uses the ContentPane object obtained using the getContentPane()method. The add() method enables you to add components to the ContentPane object. The output of the code is shown in Figure 252:

Figure 252: Frame Created Using Swing

Adding a Tool Tip and an Image Icon to a Button


You can use tool tips and images to make a program interactive and easy to understand. Tool tips are short descriptive messages that appear when you position the mouse pointer over a particular region of an application. You can add a tool tip by using the setToolTip() method of the JComponent class and retrieve the tool tip by using the getToolTipText() method. The Tool Tip manager enables you to customize the appearance of a tool tip. To access the Tool Tip manager, use the sharedInstance() method. In order to convey the purpose of a component, you can use the image icon. For example, you might use a printer icon for the print button of an application. Use the ImageIcon class to include images in your application. The Icon interface contains the definition of the methods implemented in the ImageIcon class. Listing 252 illustrates the code to add an image icon and a tool tip to a button: Listing 252: Adding an Image Icon and a Tool Tip
import javax.swing.*; import java.awt.*; import java.applet.*; public class Imageex extends JApplet {
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

JLabel image; public void init() { JPanel p=new JPanel (); getContentPane().add(p); /* The ImageIcon constructor takes the name of an image file as its parameter.*/ Icon abc=new ImageIcon ("Img14.gif"); // The label acts as a placeholder for the icon image=new JLabel(abc); image.setToolTipText("Tool Tip Example for you"); p.add(image); } }

In this example, the ImageIcon constructor uses the name of an image file as its parameter. Passing the ImageIcon object to the JLabel constructor creates the label and image. Use the setToolTipText() method to set a tool tip for the label and the add() method to add the label to the panel. The output of the code is shown in Figure 253:

Figure 253: Applet Showing a Label with an Image and a Tool Tip

Adding Borders to Swing Components


The Swing package enables you to change the appearance of a component using different borders. For example, you can add an etched border or a bevel border to a button or a label. Use the BorderFactory class of the javax.swing.border package to apply borders to a component. The Border interface has methods to draw borders around the component. Use the setBorder() method to add borders to the components and the getBorder() method to determine the borders of the components. The various types of border implementers are: Bevel border: Enables you to draw simple threedimensional (3D) borders around components. You can draw different colored lines to show depth. There are two types of Bevel borders raised and lowered. Compound border: Enables you to create a border by combining two borders, with one border nested inside the other.
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

Empty border: Occupies the space within the container to add space around the components.

Note Empty borders have replaced Insets from the AWT package. AWT is a package that contains an integrated set of classes to manage user interface components. JFC is an extension of AWT.

Matte border: Occupies space around components and enables you to add colors or image icons to the matte borders. Line border : Creates an ordinary line around components. The color class that you use to draw colored lines is a part of the java.awt package. To apply this type of border, import three packages: java.awt, javax.swing, and javax.swing.border. Etched border: Provides an etched border that shows depth. You can create an etched border by using the createEtchedBorder() method. Titled border: Enables you to display a text string on the borders around components.

Listing 253 contains the code to create a raised bevel border:


Listing 253: Creating a Raised Bevel Border

import import import import

javax.swing.*; javax.swing.border.*; java.awt.*; java.applet.*;

public class Bevelborder extends JApplet { public void init() { JPanel p=new JPanel(); getContentPane().add(p); JButton mybutton=new JButton("A Bevel Border Example"); Border bevelborder=BorderFactory.createBevelBorder(BevelBorder.RAISED); mybutton.setBorder(bevelborder); p.add(mybutton); } }

In this example, the mybutton object of the JButton class is created and assigned the caption, A Bevel Border Example. You use the createBevelBorder() method of the BorderFactory to create the bevel border, the setBorder() method to set the border around the button. The add() method is used to add a button to the panel. The output of the code is shown in Figure 254:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

Figure 254: Applet Showing a Raised Bevel Border To apply a lowered bevel border, replace the word RAISED in Listing 253 with LOWERED. The output is shown in Figure 255:

Figure 255: Applet Showing a Lowered Bevel Border Listing 254 contains the code to create a line border: Listing 254: Creating a Line Border
import import import import public { { JPanel p=new JPanel(); getContentPane().add(p); JButton mybutton=new JButton("A Line Border Example"); Borderlineborder=BorderFactory.createLineBorder(); mybutton.setBorder(lineborder); p.add(mybutton); } } javax.swing.*; javax.swing.border.*; java.awt.*; java.applet.*; class Lineborder extends JApplet

public void init()

You use the createLineBorder() method of the BorderFactory class to create a bevel border and the setBorder() method to set the border around the button. The output of the code is as shown in Figure 256:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

Figure 256: Applet Showing a Line Border Listing 255 contains the code to create an etched border: Listing 255: Creating an Etched Border
import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.applet.*; public class Etchedborder extends JApplet { public void init() { JPanel p=new JPanel(); getContentPane().add(p); JButton mybutton=new JButton("An etched Border Example"); Border etchedborder=BorderFactory.createEtchedBorder(); mybutton.setBorder(etchedborder); p.add(mybutton); } }

You use the createEtchedBorder() method of the BorderFactory class to create an etched border and the setBorder() method to set the border around the button. The output of the code is shown in Figure 257:

Figure 257: Applet Showing an Etched Border

Creating a Text Area Containing a Scroll Bar


Text areas are similar to text fields. However, a text area allows you to enter multiple lines, while a text field allows you to enter only a single line. You can specify the dimensions for a text area. For example, the code, JTextBox(5,15)creates a text area with 5 rows and 15 columns of visible text. You use scroll bars to view the remaining text. Listing 256 contains the code to create a text area component: Listing 256: Creating a Text Area with a Scroll Bar
import import import public javax.swing.*; java.awt.*; java.applet.*; class Scrollit extends JApplet
SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Reprinted for v697039, Verizon

Java ReferencePoint Suite

{ public void init() { JPanel p=new JPanel(); JTextArea ta; ta=new JTextArea(5,15); JScrollPane pane=new JScrollPane(ta); getContentPane().add(p); p.add(pane); } }

In this example, the scrollpane is created using the JScrollPane class. You add the text area component to the scroll pane that contains horizontal and vertical scroll bars. Use the add() method to add the scroll pane to the panel. The output of the code is shown in Figure 258:

Figure 258: Text Area Component with Scroll Bars

Creating a Password Field


Use the JPasswordField class to create a password field. You can use any character as an echo character for the password field. An echo character appears in the password field in place of the actual text that you type. The default echo character is an asterisk (*). Listing 257 contains the code to create a password field. Listing 257: Creating a Password Field
import javax.swing.*; import java.awt.*; import java.applet.*; public class Password extends JApplet { public void init() { JPanel p=new JPanel(); JLabel label1=new JLabel("Default Password Field"); JLabel label2=new JLabel("Echo set Password Field"); JPasswordField pw1=new JPasswordField(10); JPasswordField pw2=new JPasswordField(10); pw2.setEchoChar('?'); getContentPane().add(p); p.add(label1); p.add(pw1); p.add(label2); p.add(pw2);
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

10

} }

In this code, you use the JPasswordField class to create two password fields. The first password field has an asterisk (*) as the default echo character. Use the setEchoChar() method in the code to set a question mark (?) as the echo character for the second password field. The output of the code is shown in Figure 259:

Figure 259: Applet Showing the Password Field

Creating a List Box Control


A list box enables you to view a list of items. You use the JList class to create the list box control. The methods of the JList class are: setSelectionMode(): Is used for single or multiple selection. The parameters for this method are: SINGLE_SELECTION for selecting only single items. Index 0. For example, SetSelectionMode(0)allows you to select only single item from the list. SINGLE_INTERVAL_SELECTION for selecting a continuos list of items. MULTIPLE_INTERVAL_SELECTION for selecting multiple items in any order.

The default parameter is multiple interval selection. setVisibleRowCount(int count): Enables you to specify the number of elements that should be visible in the list. For example, the setVisibleRowCount(4) method lists four items. You can use the scroll bars to see the remaining items. getSelectedValue(): Returns the value of the selected item. If you do not select any item, this method returns a null value. If you select multiple items, the method returns the value of the first selected item. getSelectedIndex(): Returns the index of the selected item. getSelectedValues(): Returns an array of selected values.
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

11

Listing 258 contains the code to create a list box: Listing 258: Creating a List Box
import javax.swing.*; import java.awt.*; import java.applet.*; public class Listbox extends JApplet { // Declaring variables JPanel p; JLabel label1; JList list1; JButton press; public void init() { //Initialize the variables p=new JPanel(); label1=new JLabel("Shopping Cart Items"); String itemlist [] = {"Books", "Chocolates", "Trousers", "Jewelry", "Toys", "Garments" }; list1=new JList(itemlist); /* Selection mode 0 is to select only one item from the list */ list1.setSelectionMode(0); press=new JButton("BUY"); getContentPane().add(p); p.add(label1); p.add(list1); p.add(press); } }

In this example, the itemlist variable of the String datatype contains all the required items for a list. This variable is passed as a parameter to the JList class by using the statement list1=new JList(itemlist). Use the add() method to add list boxes, labels, and buttons to the panel. You can select only a single item because the selection mode is set to 0. The output of the code sample is shown in Figure 2510:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

12

Figure 2510: Applet Showing a List Box for Single Selection Set the selection mode to 1 to select multiple items in continuous order. The output for this selection mode is shown in Figure 2511:

Figure 2511: Applet Showing a List Box for Continuous Multiple Selection Set the selection mode to 2, if you want to select multiple items in any order in the list. The output for this selection mode is shown in Figure 2512:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

13

Figure 2512: Applet Showing a List Box for Multiple Selection in Any Order

Creating a Combo Box Component


A combo box resembles a dropdown menu and allows you to select only single items from a list. You can create a combo box by using the JComboBox class. A combo box provides a text field in which you can enter an item of your choice. To do this, specify true as a parameter for the setEditable() method. Use the getSelectedItem() method to retrieve selected items.

Note By default, the setEditable() method is assigned a false value. Listing 259 illustrates the code to create a combo box: Listing 259: Creating a Combo Box
import javax.swing.*; import java.awt.*; import java.applet.*; public class Combo extends JApplet { // Declaring variables JPanel p; JLabel name; JLabel dest; JComboBox combo1,combo2; JButton press; public void init() { //Initialize the variables p=new JPanel(); name=new JLabel("FLIGHT"); dest=new JLabel("DESTINATION"); String first[] = { "AIR INDIA","AIR EMIRATES", "US AIRWAYS","BRITISH AIRWAYS","SWISS AIR" }; combo1=new JComboBox(first); String second[]= { "New York","London", "Mumbai","Paris","Berlin" }; combo2=new JComboBox(second);

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

14

press=new JButton("submit"); getContentPane().add(p); p.add(name); p.add(combo1); p.add(dest); p.add(combo2); p.add(press); } }

In this code, two objects of the JComboBox class, combo1 and combo2, are created. Two variables, first and second, of the String datatype contain all the items for the combo box. The names of these variables are passed as a parameter to the JComboBox class. The output of the code is shown in Figure 2513:

Figure 2513: Applet Showing a Combo Box Make the following change in Listing 259 combo1.setEditable(true); for an editable combo box, as shown in Figure 2514:

Figure 2514: Applet Showing an Editable Combo Box

Creating a Check Box Component


Use the JCheckBox class to create a check box. You can create a selected check box by passing a true parameter to the setSelected() method. The constructors of the JCheckBox class are: JCheckBox(Icon i): Provides an icon for the checkbox

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

15

JCheckBox(Icon i, Boolean state): Provides an icon for the checkbox and sets a boolean value for the check box JCheckBox(String s): Provides a string that appears along with the check box JCheckBox(String s, Boolean state): Provides a string and a boolean value for the checkbox

Listing 2510 contains the code to create a check box: Listing 2510: Creating a Check Box
import javax.swing.*; import java.awt.*; import java.applet.*; public class Selectbox extends JApplet { JPanel p; JFrame frame=new JFrame(); JLabel name; JLabel Qual; JTextField tname,tqual; JCheckBox selection1,selection2; JButton press; public void init() { p=new JPanel(); name=new JLabel("NAME"); Qual=new JLabel("QUALIFICATION"); tname=new JTextField(5); tqual=new JTextField(5); selection1=new JCheckBox("Driving License"); selection2=new JCheckBox("Passport"); selection1.setSelected(true); press=new JButton("submit"); getContentPane().add(p); p.add(name); p.add(tname); p.add(Qual); p.add(tqual); p.add(selection1); p.add(selection2); p.add(press); } }

In this code, two check boxes are created using the JCheckBox class. Use the add() method to add these check boxes to the panel. The output of the code is shown in Figure 2515:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

16

Figure 2515: Applet Showing a Check Box

Creating a Toggle Button


A toggle button is a twostate button with active and inactive states. For example, the cut and copy buttons of an application are activated only when select some text in the application. You use the JToggleButton class to create toggle buttons. Listing 2511 contains the code to create a toggle button: Listing 2511: Creating a Toggle Button
import javax.swing.*; import java.applet.*; public class Toggle extends JApplet { public void init() { JPanel p=new JPanel(); JToggleButton tb=new JToggleButton("Toggle Button"); getContentPane().add(p); p.add(tb); } }

You use the JToggleButton class to create a toggle button and add the button to the panel by using the add() method. The output of the code is shown in Figure 2516:

Figure 2516: Applet Showing a Toggle Button

Creating a Radio Button


You use radio buttons to provide a set of options in an application. Radio buttons allow a mutually exclusive selection. An example is the male or female option in a the admission form of a university. The buttons created for a particular choice should be placed under one group. To create a button group, use the JButtonGroup class. Listing 2512 contains the code to create a radio button. Listing 2512: Creating a Radio Button
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

17

import javax.swing.*; import java.awt.*; import java.applet.*; public class Radio extends JApplet { public void init() { JPanel p=new JPanel(); JLabel status=new JLabel("Candidate Profile"); JLabel gender=new JLabel("Gender"); JButtonGroup bg1=new JButtonGroup(); JButtonGroup bg2=new JButtonGroup(); JRadioButton option1= new JRadioButton ("Married",true); JRadioButton option2= new JRadioButton ("Single"); JRadioButton option3= new JRadioButton ("Male"); JRadioButton option4= new JRadioButton ("Female"); bg1.add(option1); bg1.add(option2); bg2.add(option3); bg2.add(option4); getContentPane().add(p); p.add(status); p.add(option1); p.add(option2); p.add(gender); p.add(option3); p.add(option4); } }

The object of the JRadioButton class is created. Two groups for radio buttons, Candidate Profile and Gender, are created using the JButtonGroup class. Use the add() method to add the radio buttons to the button group. The output of the code is shown in Figure 2517:

Figure 2517: Applet Showing a Radio Button

Creating a Slider Bar


Sliders allow you to select a numerical value from a range of values. For example, you can select your height from a given range of values on a slider bar. You use the JSlider class to add sliders to an application. Listing 2513 contains the code to add sliders on an application: Listing 2513: Creating a Slider
import javax.swing.*; import java.awt.*;
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

18

import java.applet.*; public class Slider extends JApplet { public void init() { JPanel p=new JPanel(); JButton b1=new JButton("Select your weight in Pounds"); JButton b2=new JButton("Select your height in Feet"); JSlider h,v ; //Slider to show values 0 to 200 with tickspacing 20 v=new JSlider(JSlider.VERTICAL,1,10,6); v.setMajorTickSpacing(20); v.setPaintLabels(true); //Slider to show values 0 to 100 with tickspacing 10 h=new JSlider(JSlider.HORIZONTAL,0,150,20); h.setMajorTickSpacing(10); h.setPaintLabels(true); getContentPane().add(p); p.add(b2); p.add(v); p.add(h,BorderLayout.SOUTH); p.add(b1); } }

Use the setMajorTickSpacing() method to show values at intervals of 1 units each. The setPaintLabels()method is passed as a true parameter to display the label of the values. The output of the code is shown in Figure 2518:

Figure 2518: Applet Showing an Example of Creating Sliders

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Advanced Swing Programming


You can create applets by advanced swing programming using layout managers, creating menus, trees and table components, and providing user validation feature.

Layout Managers
Layout managers are objects that determine how components are located in the container of an application. Layout managers determine the size and position of the components. The various types of layout managers are: Flow Layout Manager: Positions the components one after the other. The components are placed on the next line when the layout manager reaches the border of the container. For example, the five buttons with label B1 when placed with a flow layout appear as shown in Figure 2519:

Figure 2519: Flow Layout Grid Layout Manager: Enables you to arrange and display components in a rectangular grid. This layout manager also displays components in a grid of cells, as shown in Figure 2520:

Figure 2520: Grid Layout Border Layout Manager: Enables you to position the components along the major directions: North, South, East, West and Center as shown in Figure 2521:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

20

Figure 2521: Border Layout Gridbag Layout Manager: Helps customize controls. For example, you can resize the button or place components in specified rows and columns. First, set the layout variables in a GridBagConstraints object. This object determines the constraints such as grid and weight of each component in a layout. Then, associate the constraint with the component by using the setConstraints() method. This method takes two parameters, the JClass object and the GridBagConstraints object. Use the gridx and gridy attributes to specify the row and column for the component to be displayed.

Listing 2514 contains the code to create a gridbag layout: Listing 2514: Creating a Gridbag Layout
import javax.swing.*; import java.applet.*; import java.awt.*; public class Gridbag extends JApplet { JPanel p; JLabel no; JLabel fn; JLabel ln; JLabel add; JLabel phone; JTextField tno; JTextField tfn; JTextField tln; JTextField tadd; JTextField tphone; JButton accept; GridBagLayout g1; GridBagConstraints gbc; public void init() { p=new JPanel(); getContentPane().add(p); g1=new GridBagLayout(); p.setLayout(g1); gbc=new GridBagConstraints(); no=new JLabel("ORDER NO"); fn=new JLabel("FIRST NAME"); ln=new JLabel("LAST NAME"); add=new JLabel("ADDRESS"); phone=new JLabel("PHONE"); tno=new JTextField(5); tfn=new JTextField(5); tln=new JTextField(5); tadd=new JTextField(5); tphone=new JTextField(5); accept=new JButton("ACCEPT");

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

21

gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=1; gbc.gridy=1; g1.setConstraints(no,gbc); p.add(no); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=10; gbc.gridy=1; g1.setConstraints(tno,gbc); p.add(tno); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=1; gbc.gridy=5; g1.setConstraints(fn,gbc); p.add(fn); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=10; gbc.gridy=5; g1.setConstraints(tfn,gbc); p.add(tfn); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=1; gbc.gridy=10; g1.setConstraints(ln,gbc); p.add(ln); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=10; gbc.gridy=10; g1.setConstraints(tln,gbc); p.add(tln); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=1; gbc.gridy=15; g1.setConstraints(add,gbc); p.add(add); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=10; gbc.gridy=15; g1.setConstraints(tadd,gbc); p.add(tadd); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=1; gbc.gridy=20; g1.setConstraints(phone,gbc); p.add(phone); gbc.anchor=GridBagConstraints.NORTHWEST; gbc.gridx=10; gbc.gridy=20; g1.setConstraints(tphone,gbc); p.add(tphone); gbc.anchor=GridBagConstraints.SOUTHEAST; gbc.gridx=28; gbc.gridy=25; g1.setConstraints(accept,gbc); p.add(accept); }
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

22

The g1 and gbc variables are the variables for the layout. The setConstraints() method takes two parameters. The gridx and gridy attributes of the GridBagConstraints method enable you to position the buttons, labels, and text fields. The output of the code is shown in Figure 2522:

Figure 2522: An Applet with the GridBag Layout Applied The labels and textboxes are positioned using the gridx and gridy attributes. The leftmost column has position gridx=0, and the uppermost row has position gridy=0. This is similar to the X and Y coordinates of a simple graph.

Creating a Tabbed Pane


Tabbed panes enable you to switch between multiple pages of an application by clicking a tab with a given label. Use the JTabbedPane class to create tabs in an application and the addTab() method to add tabs to the tab pane. Listing 2515 contains the code to create a tabbed pane: Listing 2515: Creating a Tabbed Pane
import javax.swing.*; public class Tabs extends JApplet { public void init() {JTabbedPane mytab=new JTabbedPane(); mytab.addTab("Administrator",new admin()); mytab.addTab("Instructor",new instructor()); mytab.addTab("Student",new student()); getContentPane().add(mytab); } } class admin extends JPanel {JButton b1,b2; JTextField t1;
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

23

public admin() { b1=new JButton("Admin Login"); t1=new JTextField(10); b2=new JButton("Click"); add(b1);add(t1);add(b2); } } class instructor extends JPanel {JButton b1,b2; JTextField t1; public instructor() { b1=new JButton("Instructor Login"); t1=new JTextField(10); b2=new JButton("Click"); add(b1); add(t1); add(b2); } } class student extends JPanel {JButton b1,b2; JTextField t1; public student() { b1=new JButton("Student Login"); t1=new JTextField(10); b2=new JButton("Click"); add(b1); add(t1); add(b2); } }

In this example, the void init()method enables you to initialize the variables of the JTabbedPane class. Use the addTab()method to add tabs to the mytab object of the JTabbedPane class. The addTab() method takes two parameters, the tab title and the class name. Use the admin class, the student class, and the instructor class to initialize the variables of the JButton and JTextField classes. The output of the code is shown in Figure 2523:

Figure 2523: Applet Showing a Tabbed Pane Similarly, when you select the Student tab, the student login form appears, as shown in Figure 2524:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

24

Figure 2524: Tabbed Pane with Student as the Active Tab

Creating Menus and Sub Menus


Before creating a menu, you need to create a menu bar by using the JMenuBar class. Add the menu bar to a frame by using the setJMenuBar()method. The frame is a container for the menu bar. Use the JMenu class to create a menu and add it to the menu bar. Next, use the JMenuItem class to create menu items and add them to the menu. Listing 2516 contains the code to create a menu and a submenu. Listing 2516: Creating a Menu and a Sub Menu
import javax.swing.*; import java.awt.*; import java.applet.*; public class Menu extends JApplet { public static void main(String args[]) { JFrame myframe=new JFrame("An example of creating Menu"); JMenuBar mybar=new JMenuBar(); myframe.setJMenuBar(mybar); JMenu eng,doc; eng=new JMenu("Engineers"); doc=new JMenu("Doctors"); mybar.add(eng); mybar.add(doc); JMenuItem compu,electro,mech,physician,surgeon; compu=new JMenuItem("Computers"); electro=new JMenuItem ("Electronics"); mech=new JMenuItem ("Mechanical"); physician=new JMenuItem ("Physician"); surgeon=new JMenuItem ("surgeon"); eng.add(compu); eng.add(electro); eng.add(mech); doc.add(physician); doc.add(surgeon); JMenu submenu=new JMenu("Status"); eng.add(submenu); submenu.add("Fresher"); submenu.add("Experienced");

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

25

myframe.setSize(400,400); myframe.setVisible(true); } }

In this example, the JFrame class is used to create a frame that is a container for the menu bar. The setSize() method enables you to set the size of the frame and the setVisible() method is passed as a true parameter to make the frame visible. Use the JMenuBar class to create a menu bar and the setJMenuBar() method to add the menu bar to the frame. The JMenu class enables you to create menus and the add() method enables you to add menu items to the menu. Create menu items using the JMenuItem class. The output of the code is shown in Figure 2525.

Figure 2525: Applet Showing a Menu Bar A sub menu is shown in Figure 2526:

Figure 2526: Applet Showing a Sub menu

Creating a Tree Component


Trees enable you to display data in a hierarchical form. You use the JTree class to create a tree component. The tree component has a super node from which other nodes arise. The super node is similar to a toplevel branch of a tree from which other branches arise. The subnodes arise from these nodes. Figure 2527 shows a diagram of a tree component:
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

26

Figure 2527: A Swing Class Hierarchy You can provide a similar presentation in your application using the JTree class. To create a tree component, add: 1. A tree object by using the JTree class. 2. A tree node by using the DefaultMutableTreeNode interface. 3. Subnodes by using the DefaultMutableTreeNode interface. 4. A scroll pane by using the JScrollPane class. 5. The tree to the scroll pane by using the add() method. 6. The scroll pane to the panel by using the add() method.

Note Use the import javax.swing.tree.* statement to include the class DefaultMutableTreeNode. Listing 2517 contains the code to create a tree component:
Listing 2517: Creating a Tree Component

import import import import

javax.swing.*; java.awt.event.*; javax.swing.tree.*; java.awt.*;

public class Tree extends JApplet { JTree tree; public void init() { // Create a super node of a tree DefaultMutableTreeNode top =new DefaultMutableTreeNode("JComponentClass");
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

27

// Create nodes for the tree DefaultMutableTreeNode button =new DefaultMutableTreeNode("JButton"); DefaultMutableTreeNode togglebutton =new DefaultMutableTreeNode("JToggleButton"); DefaultMutableTreeNode label =new DefaultMutableTreeNode("JLabel"); DefaultMutableTreeNode list =new DefaultMutableTreeNode("JList"); // Adding nodes to the super node top.add(button); top.add(togglebutton); top.add(label); top.add(list); // Create subnodes for the tree DefaultMutableTreeNode rb =new DefaultMutableTreeNode("JRadioButton"); DefaultMutableTreeNode cb =new DefaultMutableTreeNode("JCheckBox"); // Adding subnodes to the node togglebutton.add(rb); togglebutton.add(cb); // Create a tree tree=new JTree(top); // Use putClientProperty() method to change the style // of the tree. tree.putClientProperty("JTree.lineStyle","Angled"); // Create a scroll pane and add the tree to the // the scroll pane JScrollPane pane=new JScrollPane(tree); JPanel p=new JPanel(); getContentPane().add(p); // Add scroll pane to the panel p.add(pane); } }

You use the JTree class to create a tree component. The DefaultMutableTreeNode() interface enables you to create nodes for the tree. The putClientProperty() method assigns a line style to the tree. The output of the code in Listing 2517 is shown in Figure 2528:

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

28

Figure 2528: Applet Showing a Tree Component

Creating a Table Component


A table component enables you to display data in the tabular format. You use the JTable class to create a table and the constructor of the JTable class to add data and headings to the table. The syntax for the constructor is: JTable(Object data[][],Object columnheader[]). Listing 2518 contains the code to create a table component: Listing 2518: Creating a Table Component
import javax.swing.*; import java.awt.*; import java.applet.*; public class Table extends JApplet { public void init() { JPanel p=new JPanel(); String colHead[]= {"S.NO","BookTitle","Author","Publisher"}; String data[][]= { {"1","The Delicious Recipe","Susan" ,"New York Publishers "}, {"2","Unbelievable Truth","Trim et al","Triger Publishers"}, {"3","Love to Study","Kidy","DBS"} }; JTable table=new JTable(data,colHead); JScrollPane pane=new JScrollPane(table); getContentPane().add(p); p.add(pane); } }
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

29

You create a table using the JTable class. A String datatype array displays the content of the table. The variable colHead[] contain the column heading, and the variable data[][] contains the table content. The output of the code is shown in Figure 2529:

Figure 2529: Applet Showing a Table Component

UserValidation Feature
You can create applications that include the functionality to validate data. For example, you can validate the data entered in the text field of an application form and flash a message if the text field is blank. To create such applications, implement the ActionListener interface by using the keyword implements. This interface contains methods that are required to manage the event. When an event, such as a mouseclick, occurs, an ActionEvent object is generated. This object contains information such as a mouseclick event. Next, the getSource() method of the ActionEvent class returns a reference to the component that triggered the event. For example, when you click Submit button on a form, the getSource() method returns a reference to the Submit button. Listing 2519 contains the code to create an application with user validation features:
Listing 2519: Creating a User Validation Form

import import import import

javax.swing.*; java.applet.*; java.awt.*; java.awt.event.*;

public class Validation extends JApplet implements ActionListener { JPanel p; JLabel no; JTextField tno; JButton accept; public void init() { p=new JPanel(); getContentPane().add(p); no=new JLabel("ORDER NO"); tno=new JTextField(5); accept=new JButton ("ACCEPT"); p.add(no); p.add(tno); p.add(accept); accept.addActionListener(this); } public void actionPerformed (ActionEvent e) { Object obj = e.getSource(); if(obj == accept) { String no1=tno.getText();
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

30

if (no1.length()==0) {getAppletContext().showStatus("Order No not to keep blank");} } } }

You use the keyword implements to implement the ActionListener interface. When you click the Accept button, an ActionEvent object is generated. In the actionPerformed() method, the reference to the event source is retrieved using the getSource() method. Use the showStatus() method to display the message on the status bar. The output of the code is shown in Figure 2530:

Figure 2530: Applet Showing a Data Entry Validation Form

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Using Threads in a Swing Application


A thread is the smallest unit of an application that is executed by a microprocessor. For example, when you play a computer game, the graphics are displayed and the sound is played, simultaneously. You can use threads in areas, such as graphics or text animation. Listing 2520 contains the code to use threads in an application:
Listing 2520: Using Thread in a Swing Application

import javax.swing.*; import java.applet.*; import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; public class Thread_example extends JApplet implements Runnable {JLabel name; JLabel add; Thread datetime; Date date; GregorianCalendar calendar; String strdate,strtime,strstatus; public void init() {name=new JLabel("name"); add=new JLabel("address"); JPanel p=new JPanel(); getContentPane().add(p); p.add(name); p.add(add); datetime=new Thread(this); datetime.start(); } public void run() {while (datetime!=null) {display(); try {datetime.sleep(1000); } catch(InterruptedException e) { showStatus("thread interrupted");} } } public void display() { try {

date=new Date(); calendar=new GregorianCalendar(); calendar.setTime(date); strtime=calendar.get(Calendar.HOUR)+":" +calendar.get(Calendar.MINUTE)+":"+calendar.get(Calenda strdate=calendar.get(Calendar.MONTH)+"/" +calendar.get(Calendar.DATE)+"/" +calendar.get(Calenda strstatus=strtime+" "+strdate; showStatus(strstatus); } catch(Exception e) { } } }

The program imports the utility package that contains three classes: Date, Calendar, and GregorianCalendar. The Date class encapsulates the system date and time. GregorianCalendar extends from the Calendar class and displays dates according to the Gregorian calendar. The Runnable interface contains the run()method that is executed when the thread is activated. The this keyword signifies that the run() method should be invoked. Use the start() method to start the
Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

Java ReferencePoint Suite

32

thread. The setTime() method takes the Date object as an argument. Use the showStatus() method to display the date and time on the status bar of the browser. The output of the code is shown in Figure 2531:

Figure 2531: Applet Showing a Thread Example

Reprinted for v697039, Verizon

SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

You might also like