Professional Documents
Culture Documents
Reproduction and/or distribution in whole or in part in electronic, paper or other forms without written permission is 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
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.
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.
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
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.
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:
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
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.
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:
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
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:
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:
{ 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:
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:
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
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:
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:
13
Figure 2512: Applet Showing a List Box for Multiple Selection in Any Order
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);
14
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:
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:
16
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:
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:
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:
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:
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");
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
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.
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:
24
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:
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
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
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:
28
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:
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
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
30
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:
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
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: