23

Graphics Using Swing Components and Applets

LEARNING OBJECTIVES

At the end of this chapter, you will be able to understand

  • Use of Abstract Window Tool (AWT) kit.
  • Hierarchy of Graphics Software and their components and their usage.
  • Event types and event listeners.
  • Applets and their usage with swing components.
  • Converting Applet into Application and vice versa.

23.1 Graphics Programming and Applets Introduction

The programs we have seen till now had text-based output. They were uninspiring and insipid. Today's world is graphics and client server programs with audio–video integration programs. Moreover these applications are all Internet-enabled and web-based applications. Web applications use extensively graphical user interfaces (GUI). This chapter introduces you to these GUI features like frames, panels, text boxes, buttons, menus, etc. These are collectively provided in a toolkit called Advanced Windowing Tool (AWT) Kit. AWT classes provide platform-independent interfaces and their implementations. This chapter introduces you to the concept of event-driven programs, frames and panels which are extensively used in application development.

Java has been designed to be a networking language. It can claim so because it supports Applet. Applets are small java programs compiled into byte codes and the class can be transported anywhere in the network using HTML (Hyper Text Mark Up Language) Tags. The system receiving this class runs the class file imported using java virtual machine and executes the applet code on a local machine.

Finally java has introduced swing components with better feel and look than applets. This chapter handles all interfaces of AWT using Swing components only.

23.2 Hierarchy of Graphics Software

Graphical User Interface (GUI) development in JAVA is based on components. Java components can further be divided into containers and widgets, as shown in Figure 23.1.

 

Java GUI hierarchy

 

Figure 23.1 Java GUI hierarchy

Containers are further classified as Root Containers and Intermediate Containers. Root Containers, also called top-level containers, are necessary for every GUI program. Swing provides developers with three top-level containers: JFrame, JDialog and JApplet. Intermediate containers are not mandatory but are used widely as they help in managing and organizing widgets. JPanel is the most widely used intermediate container in Swing.

Widgets are GUI elements which are used to interact with the user; a typical use of widgets is to display content to user in the form of text, images, menus, buttons, checkboxes and radio buttons. Widgets are also used to get user inputs. JButton, JLabel, JScrollBar and JCheckBox are examples of widgets in Swing.

23.3 Containers in Swing

Every Java GUI application should be designed with a containment hierarchy, with the root of the hierarchy being one of the Root containers, i.e., JFrame, JDialog or JApplet. For Swing Applications the root is always JFrame. Figure 23.3 shows details.

 

Swing containment hierarchy

 

Figure 23.2 Swing containment hierarchy

 

Button

 

Figure 23.3 Button

 

Figure 23.2 shows the containment hierarchy for a program that has just one JButton widget. In the figure, the intermediate container JPanel is optional, but the top-level container is compulsory. The figure also depicts the creation and addition of rules; for java GUI programs the creation is from top to bottom, which means that we create the JFrame component first and the JButton component last, while addition starts from bottom. Example 23.1 illustrates the creation and addition rules for Java GUI programs.

 

Example 23.1:   Creating JFrame and Adding GUI Components

   1. import javax.swing.*;
   2. public class SwingDemo {
   3. public static void main(String[] args) {
   4. JFrame frame = new JFrame(“Swing Demo”);
   5. JPanel panel = new JPanel();
   6. JButton button = new JButton(“Button”);
   7.
   8. panel.add(button);
   9. frame.setContentPane(panel);
   10. frame.setVisible(true);
   11. }
   12. }

Output

As seen from the example above, we instantiate the root container frame first in line 4; we then instantiate the intermediate container panel in line 5 and finally a button widget in line 6. That is, we follow the top-down approach during creation. But during addition, we add the button to panel first in line 7 then we add the panel to the frame in line 8 and finally display the frame in line 9, thus following the bottom-up approach.

The addition and creation rules will apply to all programs discussed in this chapter.

23.3.1 JFrame Class

A frame typically provides many services; some of the more common services include ability to set the title, set icon image, provide menu bar services, set height and width of the frame, and set location of the frame. To manage the setting of the frame and to make the code reusable, we create a separate class for the frame called DisplayFrame. In DisplayFrame′s constructor we define all the default settings for our root frame. Figure 23.3 shows the details.

 

Example 23.2:   Program to Demonstrate JFrame Class

   1. import javax.swing.*;
   2. public class SwingDemo {
   3.   public static void main(String[] args) {
   4.    JFrame frame = new DisplayFrame();
   5.     frame.setVisible(true);
   6.   }
   7. }
   8. class DisplayFrame extends JFrame{
   9.   DisplayFrame(){
   10.   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   11.   setTitle(“Swing Demo”);
   12.   setSize(300, 150);
   13.   setLocation(100,100);
   14.  }
   15. }

The JFrame class is present in javax.swing.JFrame. To use this class, we use the import statement import javax.swing.*, as shown in line 1. In line 4, we instantiate the DisplayFrame object, which in turn invokes the constructor DisplayFrame( ) in line 9. Inside the constructor we set some of the settings for our root frame.

The method setDefaultCloseOperation( ) in line 10 with the parameter JFrame.EXIT_ON_CLOSE causes the frame to close whenever the user closes the frame using the close icon. The method setTitle( ) in line 11 sets the frame name. The method setSize ( ) in line 12 sets the width and height for the frame and finally the method setLocation ( ) in line 13 sets the x, y location on the screen. Output is in Figure 23.4.

 

A frame in java swing

 

Figure 23.4 A frame in java swing

23.3.2 JPanel Class

Panels are intermediate containers and as such not essential for creating Java graphical user interface programs. But panels offer a lot of flexibility in managing widgets so it is always advisable to have panels in our programs. Similar to the DisplayFrame class which extends the basic JFrame class, we create a new class called DisplayPanel which extends the JPanel class.

 

Example 23.3:   Program to Demonstrate JPanel Class

   1. import javax.swing.*;
   2. public class SwingDemo {
   3.  public static void main(String[] args) {
   4.   JFrame frame = new DisplayFrame();
   5.    frame.setVisible(true);
   6.  }
   7. }
   8. class DisplayFrame extends JFrame{
   9.   DisplayFrame(){
   10.   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   11.   setTitle(“Swing Demo”);
   12.   setSize(300, 150);
   13.   setLocation(100,100);
   14.   JPanel panel = new DisplayPanel();
   15.   getContentPane().add(panel);
   16. }
   17. }
   18. class DisplayPanel extends JPanel{
   19.  DisplayPanel() {
   20.   //Widgets will be added here
   21.    }
   22. }

The code of Example 23.3 is almost similar to Example 23.2. In the above example, we instantiate the DisplayPanel object in line 14. The constructor for DisplayPanel is presently empty but going forward, as we will see in subsequent examples, all the widget creation code will be placed inside this class. Each JFrame object has a contentpane to which all the components you want to display have to be added. Line 15 demonstrates how to get the contentpane for your frame and add the panel.

23.4 Display Widgets in Swing

Widgets are the components which help us build the user interfaces. They are the components that the user actually sees and interacts with users. Typical examples include checkboxes, buttons and menus. Java Swing provides many widgets; in subsequent sections, we discuss some of the most frequently used widgets.

23.4.1 JLabel Class

The JLabel object is used to display text, images or both text and images in Java. Figure 23.5 shows a typical use case scenario, wherein the string “Welcome to Java” is displayed using a JLabel object. Example 23.4 demonstrates how to create and display JLabel objects in Java.

 

JLabel

 

Figure 23.5 JLabel

 

Example 23.4:   Program to Demonstrate JLabel Class

   1. import javax.swing.*;
   2. public class SwingDemo {
   3.  public static void main(String[] args) {
   4.   JFrame frame = new DisplayFrame();
   5.    frame.setVisible(true);
   6.  }
   7. }
   8. class DisplayFrame extends JFrame{
   9.  DisplayFrame(){
   10.    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   11.    setTitle(“Swing Demo”);
   12.    setSize(300, 150);
   13.    setLocation(100,100);
   14.    JPanel panel = new DisplayPanel();
   15.    getContentPane().add(panel);
   16.  }
   17. }
   18. c DisplayPanel extends JPanel{
   19. DisplayPanel() {
   20. JLabel label = new JLabel
   21. (“Welcome to Java Swing” );
   22. add(label);
   23. }
   24. }

The JLabel class is present in javax.swing.JLabel. To use this class, we use the import statement import javax.swing.*, as shown in line 1. We instantiate the JLabel object in line 20; the string to be displayed is passed as a parameter during instantiation. Finally, we add the JLabel object label to the panel in line 22.

23.4.2 JButton

The JButton object is used to display buttons in Java. Buttons are very useful user interface elements, which can be used for a variety of user interactions. Figure 23.6 shows a typical use case scenario, wherein the button "Click Me" is displayed using a JButton object. Example 23.5 demonstrates how to create and display JButton objects in Java.

 

JButton

 

Figure 23.6 JButton

 

Example 23.5:   Program to Demonstrate JButton Class

   1. import javax.swing.*;
   2. public class SwingDemo {
   3.  public static void main(String[] args) {
   4.   JFrame frame = new DisplayFrame();
   5.     frame.setVisible(true);
   6.  }
   7. }
   8. class DisplayFrame extends JFrame{
   9.  DisplayFrame(){
   10.   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   11.   setTitle(“Swing Demo”);
   12.   setSize(300, 150);
   13.   setLocation(100,100);
   14.   JPanel panel = new DisplayPanel();
   15.   getContentPane().add(panel);
   16.  }
   17. }
   18. class DisplayPanel extends JPanel{
   19. DisplayPanel() {
   20. JButton button = new JButton(“Click Me”);
   21. add(button);
   22. }
   23. }

The JButton class is present in javax.swing.JButton. To use this class, we use the import statement import javax.swing.*, as shown in line 1. We instantiate the JButton object in line 20.

The string to be displayed is passed as a parameter during instantiation. Finally, we add the JButton object button to the panel in line 21.

23.4.3 JCheckBox

The JCheckBox object is used to display checkboxes in Java. Checkboxes allow users to either select or deselect an item; they also allow multiple items to be selected at the same time. The figure below shows a typical use case scenario, wherein three checkboxes “Cricket”, “Football” and “Volleyball” are displayed using a JCheckBox object. Example 23.6 demonstrates how to create and display JCheckBox objects in Java. Figure 23.7 shows the output.

 

JCheckbox

 

Figure 23.7 JCheckbox

 

Example 23.6:   Program to Demonstrate JCheckBox Class

   1. import java.awt.event.KeyEvent;
   2. import javax.swing.*;
   3. public class SwingDemo {
   4.  public static void main(String[] args) {
   5.   JFrame frame = new DisplayFrame();
   6.     frame.setVisible(true);
   7.  }
   8. }
   9. class DisplayFrame extends JFrame{
   10. DisplayFrame(){
   11.   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   12.   setTitle(“Swing Demo”);
   13.   setSize(400, 150);
   14.   setLocation(100,100);
   15.   JPanel panel = new DisplayPanel();
   16.   getContentPane().add(panel);
   17.  }
   18. }
   19. class DisplayPanel extends JPanel{
   20.  DisplayPanel() {
   21.    JCheckBox cb1 = new JCheckBox(“Cricket”);
   22.    cb1.setMnemonic(KeyEvent.VK_C);
   23.   cb1.setSelected(false);
   24.   JCheckBox cb2 = new JCheckBox(“Football”);
   25.   cb2.setMnemonic(KeyEvent.VK_F);
   26.   cb2.setSelected(false);
   27.   JCheckBox cb3 = new JCheckBox(“Volleyball”);
   28.   cb3.setMnemonic(KeyEvent.VK_V);
   29.   cb3.setSelected(false);
   30.   add(cb1);
   31.     add(cb2);
   32.     add(cb3);
   33.  }
   34. }

The JCheckBox class is present in javax.swing.JCheckBox. To use this class, we use the import statement import javax.swing.*, as shown in line 2. We instantiate the JCheckBox object in line 21; the string to be displayed is passed as a parameter during instantiation. The method setMnemonic() allows users to select or deselect items in checkboxes using keyboard keys. The statement in line 22 uses the setMnemonic method, thereby allowing users to select or deselect the Cricket checkbox using ALT + C button combination on the keyboard. The setMnemonic() function takes a KeyEvent as the input parameter; KeyEvents are represented using the syntax VK_*, for example, C is represented as VK_C. KeyEvents are defined in java.awt.event.KeyEvent. To use KeyEvents in our program, we use the import statement import java.awt.event.KeyEvent, as shown in line 1. setSelected () method as seen in line 23 is used to set the initial state for a checkbox; false indicates that the checkbox is initially deselected. We follow the same procedure of instantiating a checkbox and setting its properties for other checkboxes as well. Finally, we add the JCheckBox objects cb1, cb2 and cb3 to the panel in lines 30, 31, and 32.

23.4.4 JComboBox

The JComboBox object is used to display checkboxes in Java. Combo boxes in Java have a button and a drop-down list. The button is used to activate the drop-down list. Combo boxes offer the advantage of space and at the same time provide functionality of letting the user choose a particular item from a list of items. The attached figure shows a typical use case scenario, wherein on pressing the down arrow button of the Combo box, a drop-down list containing names of various cities is displayed to the user using a JComboBox object. Example 23.7 demonstrates how to create and display JComboBox objects in Java. Figure 23.8 shows the output.

 

JCombo box

 

Figure 23.8 JCombo box

 

Example 23.7:   Program to Demonstrate JComboBox Class

   1. import javax.swing.*;
   2. public class SwingDemo {
   3.  public static void main(String[] args) {
   4.    JFrame frame = new DisplayFrame();
   5.      frame.setVisible(true);
   6.  }
   7. }
   8. class DisplayFrame extends JFrame{
   9.   DisplayFrame(){
   10.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   11.     setTitle(“Swing Demo”);
   12.     setSize(300, 150);
   13.     setLocation(100,100);
   14.     JPanel panel = new DisplayPanel();
   15.     getContentPane().add(panel);
   16.  }
   17. }
   18. class DisplayPanel extends JPa nel{
   19. DisplayPanel() {
   20. String[] cities = { “Delhi”, “London”, “New York”, “Moscow”, “Mumbai” };
   21.    JComboBox citylist = new JComboBox(cities);
   22.    citylist.setSelectedIndex(2);
   23.    add(citylist);
   24.  }
   25. }

The JComboBox class is present in javax.swing.JComboBox. To use this class, we use the import statement import javax.swing.*, as shown in line 1. In line 20, we define cities, an array of Strings, which contains the names of all the items we would like to display in our drop-down list. We instantiate the JComboBox object in line 21; the array cities is passed as a parameter during instantiation. The setSelectedIndex() method in line 22 shows how to set the default display item for the combo box. We have passed 2 as the parameter to setSelectedIndex(), so when the combo box is instantiated, the default item displayed will be “New York” as the String New York is present at index 2 in the array cities. Finally, we add the JComboBox object citylist to the panel in line 23.

23.4.5 JMenu Class

Menus in Java are implemented using three components, namely, JMenuBar, JMenu and JMenuItems. Menu bar is generally located at the top of the window; it contains one or more menus. When we click on the menu, a list appears which contains user selectable menu items or in some cases a submenu. The figure below shows a typical use case scenario, wherein the menu bar has two menus, File and Window. The menu Window has two menu items, New Window and New Editor, and a submenu called Options. Example 23.8 demonstrates how to create and display complete menus using JMenuBar, JMenu and JMenuItem objects in Java. Output is shown in Figure 23.9.

 

JMenu

 

Figure 23.9 JMenu

 

Example 23.8:   Program to Demonstrate JMenu Class

   1. import javax.swing.*;
   2. public class SwingDemo {
   3.   public static void main(String[] args) {
   4.     JFrame frame = new DisplayFrame();
   5.       frame.setVisible(true);
   6.  }
   7. }
   8. class DisplayFrame extends JFrame{
   9.  DisplayFrame(){
   10.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   11.     setTitle(“Swing Demo”);
   12.     setSize(300, 150);
   13.     setLocation(100,100);
   14.   JMenuBar MenuBar = new JMenuBar();
   15.   JMenu menu = CreateFileMenu();
   16.   MenuBar.add(menu);
   17.   menu = CreateWindowMenu();
   18.   MenuBar.add(menu);
   19.   setJMenuBar(MenuBar);
   20. }
   21. private JMenu CreateFileMenu() {
   22.   JMenu menu = new JMenu(“File”);
   23.   JMenuItem item = new JMenuItem("Open");
   24.   menu.add(item);
   25.   item = new JMenuItem("Close");
   26.   menu.add(item);
   27.   menu.addSeparator();
   28.   item = new JMenuItem("Exit");
   29.   menu.add(item);
   30.   return menu;
   31. }
   32. private JMenu CreateWindowMenu() {
   33.   JMenu menu = new JMenu("Window");
   34.   JMenuItem item = new JMenuItem("New Window");
   35.   menu.add(item);
   36.   item = new JMenuItem("New Editor");
   37.   menu.add(item);
   38.   menu.addSeparator();
   39.   JMenu submenu = new JMenu(“Options”);
   40.   item = new JMenuItem("Default");
   41.   submenu.add(item);
   42.   item = new JMenuItem("Delete");
   43.   submenu.add(item);
   44.   menu.add(submenu);
   45.   return menu;
   46. }
   47. }

The JMenuBar, JMenu and JMenuItem classes are present in javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JItem, respectively. To use these classes, we use the import statement import javax.swing.*, as shown in line 1. We define two functions CreateFileMenu( ) in line 21 and CreateWindowMenu( ) in line 32. The function CreateFileMenu( ) instantiates a menu with the name “File” in line 22; it also creates two menu items “Close” and “Exit” in lines 25 and 28 and adds these menu items to the File menu in lines 26 and 29. The addSeparator( ) method adds a line between the two menu items in File Menu. The CreateWindowMenu( ) function creates a menu “Window” and populates it with two menu items “New Editor” and “New Window”. The function also creates a submenu “Options” in line 39, adds menu items “Default” and “Delete” and then adds the submenu to the Window menu in line 44.

Menu bar is instantiated in line 14, the menus “File” and “Windows” are instantiated in lines 15 and 17 and added to the menu bar in lines 16 and 18. The menu bar differs from other widgets discussed till now as a menu bar is added to the Frame rather than to an intermediate panel. The method setJMenuBar( ) is used to add the menu bar to the frame, as shown in line 19.

23.5 Layout Managers

Till now we have discussed about creation of widgets; most of our examples so far have single widgets. But in real-life scenarios, we will have multiple widgets on the same screen and we need some kind of layout management to manage the placement of these widgets on the screen. Java Swing provides us with three Layout managers to simplify our task. In subsequent sections, we will have a closer look at these layout managers.

23.5.1 Border Layout

Border layout divides the panel into five regions: North, South, East, West and Center, as shown below. In Border Layout, the widgets present in the North, South and Center expand to fill the available width whereas the widgets in the East and West regions expand as per the widget contents. Example 23.9 illustrates how to arrange widgets in Border Layout. Figure 23.10 shows the output.

 

Border layout

 

Figure 23.10 Border layout

 

Example 23.9:   Program to Demonstrate Border Layout

   1. import java.awt.*;
   2. import javax.swing.*;
   3. import javax.swing.border.Border;
   4. public class SwingDemo {
   5.   public static void main(String[] args) {
   6.     JFrame frame = new DisplayFrame();
   7.       frame.setVisible(true);
   8.  }
   9. }
   10. class DisplayFrame extends JFrame{
   11.   DisplayFrame(){
   12.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   13.     setTitle(“Swing Demo”);
   14.     setSize(400, 150);
   15.     setLocation(100,100);
   16.     JPanel panel = new DisplayPanel();
   17.     getContentPane().add(panel);
   18.  }
   19. }
   20. class DisplayPanel extends JPanel{
   21.  DisplayPanel() {
   22.    setLayout(new BorderLayout());
   23.     add(new newLabel(“NORTH”), BorderLayout.NORTH);
   24.     add(new newLabel(“SOUTH”), BorderLayout.SOUTH);
   25.     add(new newLabel(“EAST”), BorderLayout.EAST);
   26.     add(new newLabel(“WEST”), BorderLayout.WEST);
   27.     add(new newLabel(“CENTER”),BorderLayout.CENTER);
   28.  }
   29. class newLabel extends JLabel {
   30.   Border black = BorderFactory.createLineBorder(Color.black);
   31.     newLabel(String S){
   32.    setText(S);
   33.    setHorizontalAlignment(CENTER);
   34.    setBorder(black);
   35.    }
   36.  }
   37. }

The panel layout is set using the method setLayout( ) and passing an instance of the class BorderLayout, as seen in line 22. We use the add( ) method to populate the panel with newLabel widgets along with the location information, as seen in lines 23 to 27. The newLabel widget is an extension of JLabel with additional properties. It sets the alignment of text in the label so that the text appears centered; this is achieved using the method setHorizontalAlignment( ) and passing the parameter CENTER, as seen in line 33. We also set a black border for the label so that the area occupied by the label is clearly visible. This is achieved using the method setBorder( ) and passing the parameter black, as seen in line 34. The parameter black is of the type Border which is created in line 30. You can create different line colours by changing the parameter in createLineBorder( ).

23.5.2 Grid Layout

Grid Layout divides the screen into specified rows and columns as seen in the figure shown below. Grid layout is useful when we want to create UI similar to windows desktop wherein the icon is symmetrically placed in the screen. Figure 23.11 shows the output.

 

GridLayout

 

Figure 23.11 GridLayout

 

Example 23.10:   Program to Demonstrate Grid Layout

   1. import java.awt.*;
   2. import javax.swing.*;
   3. import javax.swing.border.Border;
   4. public class SwingDemo {
   5.   public static void main(String[] args) {
   6.   JFrame frame = new DisplayFrame();
   7.   frame.setVisible(true);
   8.   }
   9. } Figure 23.11 GridLayout
   10. class DisplayFrame extends JFrame{
   11.  DisplayFrame(){
   12.    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   13.    setTitle(“Swing Demo”);
   14.    setSize(300, 150);
   15.    setLocation(100,100);
   16.    JPanel panel = new DisplayPanel();
   17.    getContentPane().add(panel);
   18.  }
   19. }
   20. class DisplayPanel extends JPanel{
   21.   DisplayPanel() {
   22.  setLayout(new GridLayout(3, 3));
   23.   for(int i = 1; i <= 9 ; i++ ){
   24.     add(new CalcLabel(Integer.toString(i)));
   25.   }
   26. }
   27. class CalcLabel extends JLabel {
   28.   CalcLabel(String S){
   29.    Border black = BorderFactory.createLineBorder(Color.BLACK);
   30.    setText(S);
   31.    setHorizontalAlignment(CENTER);
   32.    setBorder(black);
   33.   }
   34.  }
   35. }

Similar to Example 23.9, the only difference is in the GridLayout instantiation, as seen in line 22. We need to specify the number of rows and columns in our present example; the number of rows and columns are three.

23.5.3 Flow Layout

Flow layout is the default layout. If you do not specify any layout using the setLayout() method, then by default, the panel will have a Flow layout. In flow layout, the widgets are arranged form left to right and then from top to bottom. Flow layout can be seen in Figure 23.7 wherein all the checkboxes are arranged from left to right.

23.6 Event Types and Event Listeners

GUI programming in Java involves two parts. The first part involves creating user interface using various components, containers and widgets, whereas the second part involves handling events that are generated due to the user interaction. Events are generated due to user activity and they can range from key presses, mouse clicks to selecting/deselecting checkboxes and button clicks. The Java Abstract windowing Toolkit (AWT) framework is responsible for delivering user-generated events to the applications. AWT also defines the interfaces for all the event handlers.

Events in Java can be classified into two types: high-level events and low-level events. High-level events such as Action events are specific to certain widgets and are sent to the application only if those widgets are present and have registered for the event. In contrast low-level events such as Keyboard and Mouse events are sent to all the widgets which have registered to receive them. In the subsequent sections, we discuss some of the most commonly encountered events and their handling mechanisms.

23.6.1 Action Event Listener

Action events are one of the most common events in Java. They are generated whenever the user performs any action on the widget like pressing a button or choosing an item from the menu. To enable us to handle action events, we need to create a class that implements the ActionListener interface. The ActionListener interface requires us to implement just one method actionPerformed(ActionEvent e). The function actionPerformed() is invoked whenever the user performs an action on the widget. Example 23.12 illustrates how to create an action event handler and handle action events.

 

Example 23.11:   Program to Demonstrate Action Event Handling

   1. import java.awt.*;
   2. import java.awt.event.*;
   3. import javax.swing.*;
   4. public class SwingDemo {
   5.   public static void main(String[] args) {
   6.    JFrame frame = new DisplayFrame();
   7.      frame.setVisible(true);
   8.   }
   9. }
   10. class DisplayFrame extends JFrame{
   11.   DisplayFrame(){
   12.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   13.     setTitle(“Swing Demo”);
   14.     setSize(300, 150);
   15.     setLocation(100,100);
   16.     JPanel panel = new DisplayPanel();
   17.     getContentPane().add(panel);
   18.  }
   19. }
   20. class DisplayPanel extends JPanel{
   21.   int count;
   22.   JLabel label;
   23.   JButton button;
   24.   DisplayPanel() {
   25.    count = 0;
   26.    button = new JButton(“Click Me”);
   27.    label = new JLabel();
   28.    label.setText(“Count = “ +count);
   29.    button.addActionListener(new HandleEvent());
   30.     add(button);
   31.     add(label);
   32.  }
   33. class HandleEvent implements ActionListener{
   34.  public void actionPerformed(ActionEvent e) {
   35.    count ++;
   36.    label.setText(“Count = “ +count);
   37.   }
   38.  }
   39. }

The program above is used to count the number of times the user has pressed the button “Click Me”. The count is updated on the screen, as shown in Figure 23.13. At the start of the program, the count is 0 after 12 clicks by the user the count shows 12. Updating the count on button press is done by the class HandleEvent line 33 which implements the ActionListener interface. As discussed above, any class implementing the ActionListener should implement the method actionPerformed(). This is done in line 34. The function actionPerformed() is invoked whenever the user presses the button “Click Me”. In this function, we update the count variable in line 35 and update the label which displays the count using JLabels setText() function call in line 36. We have implemented the HandleEvent class as an inner class to DisplayPanel as it needs to use the variables count and label defined in DisplayPanel class. Line 29 button.addActionListener (new HandleEvent()) shows how to bind the action event handler with the button widget. Binding widget with event handler as done in line 29 is absolutely essential else the events will not be sent to the event handler.

 

Output of Example 23.1

 

Figure 23.12 Output of Example 23.11

 

Output of Example 23.12

 

Figure 23.13 Output of Example 23.12

23.6.2 Item Event Listener

Item events are generally fired by components such as checkboxes, radio buttons and combo boxes wherein the user selects or deselects an item. To enable us to handle item events in our program, we need to create a class that implements the ItemListener interface.

The ItemListener interface requires us to implement one method itemStateChanged (ItemEvent e). The function itemStateChanged () is invoked whenever the user selects or deselects an item in the widget. Example 23.12 illustrates how to create an item event handler and handle item events. Figure 23.13 shows the output.

 

Example 23.12:   Program to Demonstrate Item Event Handling

   1. import java.awt.*;
   2. import java.awt.event.*;
   3. import javax.swing.*;
   4. public class SwingDemo {
   5.   public static void main(String[] args) {
   6.     JFrame frame = new DisplayFrame();
   7.       frame.setVisible(true);
   8.   }
   9. }
   10.  class DisplayFrame extends JFrame{
   11.  DisplayFrame(){
   12.      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   13.      setTitle(“Swing Demo”);
   14.      setSize(400, 150);
   15.      setLocation(100,100);
   16.      JPanel panel = new DisplayPanel();
   17.      getContentPane().add(panel);
   18. }
   19.  }
   20. class DisplayPanel extends JPanel{
   21.    JLabel label;
   22.    JCheckBox cb1;
   23.    JCheckBox cb2;
   24.    JCheckBox cb3;
   25.  DisplayPanel() {
   26.    cb1 = new JCheckBox(“Cricket”);
   27.    cb1.setMnemonic(KeyEvent.VK_C);
   28.    cb1.setSelected(false);
   29.    cb2 = new JCheckBox(“Football”);
   30.    cb2.setMnemonic(KeyEvent.VK_F);
   31.    cb2.setSelected(false);
   32.    cb3 = new JCheckBox(“Volleyball”);
   33.    cb3.setMnemonic(KeyEvent.VK_V);
   34.    cb3.setSelected(false);
   35.    JLabel display_label = new JLabel();
   36.    display_label.setText(“Select Favorite Game”);
   37.    label = new JLabel();
   38.    label.setText(“”);
   39.    HandleItemEvent handler = new HandleItemEvent();
   40.    cb1.addItemListener(handler);
   41.    cb2.addItemListener(handler);
   42.    cb3.addItemListener(handler);
   43.    add(display_label);
   44.    add(cb1);
   45.    add(cb2);
   46.    add(cb3);
   47.    add(label);
   48.
   49.  }
   50. class HandleItemEvent implements ItemListener{
   51.  public void itemStateChanged(ItemEvent e) {
   52.    int index = 0;
   53.    Object source = e.getItemSelectable();
   54.    if (source == cb1) {
   55.      index = 1;
   56.    } else if (source == cb2) {
   57.   index = 2;
   58.  } else if (source == cb3) {
   59.    index = 3;
   60.  }
   61.  if (e.getStateChange() == ItemEvent.DESELECTED) {
   62.     label.setText(“Game at index: “ +index + “ Deselected”);
   63.  }
   64. if (e.getStateChange() == ItemEvent.SELECTED) {
   65.     label.setText(“Game at index: “ +index + “ Selected”);
   66.     }
   67.    }
   68.   }
   69. }

The program above is designed to get the users favourite sport. As it is a checkbox, multiple selections are possible. The label below the checkboxes records the index of the latest selection; index 1 implies cricket. The label is dynamically updated each time the user selects or deselects a sport. Updating the label is done in the class HandleItemEvent defined in line 50 which implements the ItemListener interface. The HandleItemEvent class is instantiated in line 39 and is bound to the three checkboxes in lines 40, 41 and 42. The example demonstrates how a single handler can be bound to multiple sources. To identify which checkbox has fired an item event we use the method getItemSelectable( ), as shown in line 53. Once we know the source, we update the index accordingly as seen in lines 54 to 60. To know whether the item in the widget has been selected or deselected, we use the method getStateChange( ). The return value of this method can be compared with the SELECTED and DESELECTED constants defined in ItemEvent. Both the methods getItemSelectable( ) and getStateChange( ) are also defined in the ItemEvent object that is passed as an argument to the event handler.

23.6.3 Keyboard Event Listener

Key events are generated whenever the user presses and releases keys on the keyboard. As described earlier, key events are low-level events and all widgets can register for key events. For widgets to receive key events it is essential that the widget has focus. To handle key events, we need to define a class that implements the KeyListener interface. The KeyListener interface defines three functions:

keyPressed(KeyEvent key): This method is invoked when the user presses any key on the keyboard.

keyReleased(KeyEvent key): This method is invoked when the user releases the pressed key on the keyboard.

keyTyped(KeyEvent key): This method is invoked whenever the user presses a printable key such as the characters a,b,c or symbols such as +, _ , or * on the keyboard. The difference between KeyPressed and KeyTyped methods is that KeyTyped method is invoked only when user types printable keys while KeyPressed method is invoked for all the keys such as function keys F1, F2, HOME, INSERT and DELETE keys.

Example 23.13 illustrates how to create a key event handler and handle key events. The output is shown in Figure 23.14.

 

image

 

Figure 23.14 Keyboard event

 

Output of Example 23.14

 

Figure 23.15 Output of Example 23.14

 

Example 23.13:   Program to Demonstrate Key Event Handling

   1. import java.awt.*;
   2. import java.awt.event.KeyEvent;
   3. import java.awt.event.KeyListener;
   4. import javax.swing.*;
   5. public class SwingDemo {
   6.   public static void main(String[] args) {
   7.    JFrame frame = new DisplayFrame();
   8.     frame.setVisible(true);
   9.   }
   10. }
   11. class DisplayFrame extends JFrame{
   12.  DisplayFrame(){
   13.    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   14.    setTitle(“Swing Demo”);
   15.    setSize(300, 150);
   16.    setLocation(100,100);
   17.    JPanel panel = new DisplayPanel();
   18.    getContentPane().add(panel);
   19.  }
   20. }
   21. class DisplayPanel extends JPanel{
   22.   String msg = “”;
   23.   JLabel label;
   24.   DisplayPanel() {
   25.   label = new JLabel(msg);
   26.   label.addKeyListener(new HandleKeyEvent());
   27.   label.setFocusable(true);
   28.   JLabel disp_label = new JLabel(“Enter Text”);
   29.   add(disp_label);
   30.   add(label);
   31. }
   32. class HandleKeyEvent implements KeyListener{
   33.   public void keyPressed(KeyEvent ke) {
   34.    int key = ke.getKeyCode();
   35.    switch(key)
   36.  {
   37.  case KeyEvent.VK_HOME:
   38.    msg += “HOME”;
   39.    break;
   40.  case KeyEvent.VK_INSERT:
   41.    msg += “INSERT”;
   42.    break;
   43.  case KeyEvent.VK_DELETE:
   44.    msg += “DELETE”;
   45.    break;
   46.  case KeyEvent.VK_END:
   47.    msg += “END”;
   48.    break;
   49.  }
   Listener
   50.    label.setText(msg);
   51.     }
   52.     public void keyReleased(KeyEvent ke)
   53.     {
   54.     }
   55.     public void keyTyped(KeyEvent ke)
   56.     { msg += ke.getKeyChar();
   57.       label.setText(msg);
   58.     }
   59.   }
   60. }

The application above updates a label dynamically each time the user enters a key on the keyboard. Updating the label is done in the class HandleKeyEvent defined in line 32 which implements the KeyListener interface. The HandleKeyEvent class is instantiated and bound to the label in line 26. As discussed earlier, it is mandatory for widgets wanting to receive key events to have focus. This is achieved using the method label.setFocusable(true) in line 27. In case of a non-printable keys, we use the method getKeyCode( ) line 34 to retrieve the key pressed and in the case of printable keys we retrieve the key using the method getKeyChar( ) in line 56. Both the methods are defined in KeyEvent object which is passed as an argument to the event handler functions. As seen from the code, the method getKeyCode returns an integer constant. We use a switch statement to identify and process the special keys. The function keyRelased( ) is a dummy function but he have to define it as it as specified in the interface else we will get compilation errors.

23.6.4 Mouse Event Listener

Mouse events like the key events are low-level events. To handle the mouse events, we need to define a class that implements the MouseListener interface. The MouseListener interface defines five functions

mouseEntered(MouseEvent e): This method is invoked when the cursor enters the widget area.

mouseExited(MouseEvent e): This method is invoked when the cursor leaves the widget area.

mousePressed(MouseEvent e): The method is invoked when the user presses the mouse button.

mouseReleased(MouseEvent e): The method is invoked when the user releases the mouse button.

mouseClicked(MouseEvent e): The method is invoked when the user clicks, that is, presses and releases, the mouse button.

Example 23.14 illustrates how create a mouse event handler and handle mouse events. Figure 23.15 shows the output.

 

Example 23.14:   Program to Demonstrate Mouse Event Handling

   1. import java.awt.*;
   2. import java.awt.event.*;
   3. import javax.swing.*;
   4. public class SwingDemo {
   5.   public static void main(String[] args) {
   6.    JFrame frame = new DisplayFrame();
   7.     frame.setVisible(true);
   8.   }
   9. }
   10. class DisplayFrame extends JFrame{
   11.   DisplayFrame(){
   12.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   13.     setTitle(“Swing Demo”);
   14.     setSize(300, 150);
   15.    setLocation(100,100);
   16.    JPanel panel = new DisplayPanel();
   17.    getContentPane().add(panel);
   18.  }
   19. }
   20. class DisplayPanel extends JPanel{
   21.   int count;
   22.   JLabel label;
   23.   JButton button;
   24.
   25.   DisplayPanel() {
   26.    count = 0;
   27.    button = new JButton(“Click Me”);
   28.    label = new JLabel();
   29.    label.setText(“Count = “ +count);
   30.    button.addMouseListener(new HandleMouseEvent());
   31.    add(button);
   32.    add(label);
   33.    setBackground(Color.WHITE);
   34.  }
   35. class HandleMouseEvent implements MouseListener{
   36.   public void mouseClicked(MouseEvent e) {
   37.    count++;
   38.   label.setText(“Count = “ +count);
   39.  }
   40.   public void mouseEntered(MouseEvent e) {
   41.
   42.   setBackground(Color.YELLOW);
   43.  }
   44.  public void mouseExited(MouseEvent e) {
   45.   setBackground(Color.WHITE);
   46.
   47.  }
   48.  public void mousePressed(MouseEvent e) {
   49.
   50. }
   51.   public void mouseReleased(MouseEvent e) {
   52.
   53. }
   54. }
   55. }

In this example, we handle two tasks: one is count the number of times the user has clicked the button “Click Me” and the second involves setting the background colour of the panel Yellow each time the cursor is in the button area. To achieve these tasks, we use a mouse event handler called HandleMouseEvent which implements the MouseListener in line 35. The HandleMouseEvent is instantiated and bound to the button widget in line 30. As seen from the code, we update the count and set the Label in lines 37 and 38. The colour of the panel is changed using the method setBackground( ), as seen in lines 42 and 45.

23.7 Applets

Applets are small java programs that are transported from one computer system on the network to another system. They cannot be run independently but they need web browser or program called appletviewer to run on the system.

An applet, just like an application, can perform lot of tasks such as computation, taking user inputs, passing parameters, display using Graphics-rich features, play music and last but not least create animations. But the beauty is that applet can travel on computer from one location to another embedded onto HTML Tags when user imports them using Internet.

23.7.1 Concepts of Applets

An applet is a java program that requires another host program to run it, i.e., Applet program gets embedded in another program and gets executed. Applets are run from web browsers such as IE or Google Chrome. Applet programming is Java's way to provide the user with excellent graphics and GUI facilities, in addition to other conveniences such as distributed and object-oriented features.

We have Applet class with hierarchy java->applet->Applet. So the applet class we are going to write must extend to package java.applet.Applet. The details are in Figure 23.16.

 

Class hierarchy of applets in java

 

Figure 23.16 Class hierarchy of applets in java

23.7.2 Life Cycle of an Applet

There are four states in a life of an applet: Born, Running, Idle and Dead. They are explained in the diagram shown in Figure 23.17.

 

Life cycle of an applet

 

Figure 23.17 Life cycle of an applet

Initialization: Applet when it is born calls init() method that sets initial conditions such as create objects needed, set font and colour and images, set up sizes of window and set up initial values. Usually we need to write our own init () method to override base class init() method.

Running: When an applet is created, it enters a Running state when it calls for a start() method. Start() method is called automatically on initialization of applet by init() method. An applet which is in idle state can also be started. Therefore, we can say that start(0) method can be called any number of times.

Idle/Stop(). An applet goes to idle state when a stop(0) method is called. This stop() is called automatically whenever web page running the applet is left. If an applet is running on a thread, then the thread will be stopped.

Dead state: It is a state when an applet is removed from the main memory. A method called destroy() is used to clean up any memory spaces.

Display state: This occurs when applet runs paint() method or a panel object is added to Container object as in the case of Applets with swing components.

To summarize, the methods that are invoked when an applet or JApplet is loaded by any browser, there are four methods which are automatically initiated by the browser. They are

  • Init(): Initiated automatically whenever an Applet is loaded. It is like a constructor. It initially creates the applet including initialization of threads.
  • Start(): Automatic whenever init() is called.
  • Stop(): Invoked automatically whenever destroy() method is called.
  • Destroy(): Invoked automatically whenever browser is terminated. Threads have to be stopped and removed in this section.
  • Paint(Graphics g): Invoked automatically whenever start() is called.
  • Update(Graphics g): After paint(), update() updates the container.

Repaint(Graphics g): invokes update() which calls paint() which in turn calls update() to update the container.

23.7.3 Creating an Applet – HelloWorld Applet

In our first example, we will write an applet program to highlight the issues and commands we use to set applet work. Applet Programming has two distinct stages:

  • Develop Applet Program and compile just like ordinary java application. Output will be HelloWorldApplet.class.
  • Write HTML (Hyper Text Mark Up Language) Tags shown below in any text editor and name the file as HelloWorldApplet.html. Embed applet tag in the html file.
  • Execute the applet program by using appletviewer or web browser. Details are shown below.

 

Example 23.15:   HelloWorldApplet.java With Html Tags Embedded in the Main Java Programme. This Code Can Only be Executed with Appletviewer

   1. /* <HTML>
   2. <BODY>
   3. <Applet Code=”HelloWorldApplet.class” Height=320 Width=400>
   4. </Applet>
   5. </BODY>
   6. </HTML>
   7. */
   8. import java.awt.*;
   9. import java.applet.*;
   10. import java.awt.Graphics.*;
   11. public class HelloWorldApplet extends Applet {
   12. public void paint(Graphics g) {
   13. g.drawString(«Hello There !This is how Applets look & feel !», 65 , 95);
   14. }
   15. }

Compilation: Go to the Directory where the java file has been entered.

javac HelloWorldApplet.java

Appletviewer HelloWorldApplet.java Output is shown in Figure 23.18

 

An applet output

 

Figure 23.18 An applet output

 

Example 23.16:   HelloWorldApplet.java with HTML File Separately Created and Class File is Embedded in HTML File. This Code Can be Executed with AppletViewer or Web Browser.

   //HelloWorldApplet.java
   1. import java.awt.*;
   2. import java.applet.*;
   3. import java.awt.Graphics.*;
   4. public class HelloWorldApplet extends Applet {
   5. public void paint(Graphics g) {
   6. g.drawString(“Hello There !This is how Applets look & feel !”, 65, 95);
   7. }
   8. }

   Compile: javac HelloWorldApplet.java

   In the same directory create a separate html file called HelloWorldApplet.html

   1. <HTML>
   2. <BODY>
   3. <Applet Code=”HelloWorldApplet.class” Height=320 Width=400>
   4. </Applet>
   5. </BODY>
   6. </HTML>

Running of program:

   Appletviewer HelloWorldApplet.html

   Or go to icon of web browser in the directory where html file has been created and double press on the icon.

The import statements direct the Java compiler to include the java.applet.* and java.Graphics.* As Applet classes use extensively the features of windows, we also need to import a package called awt that stands for Advanced Windowing ToolKit (awt).

The Hello class extends Applet class; the Applet class provides the framework for the host application to display and control the lifecycle of the applet. The Applet class provides the applet with the capability to display GUI and respond to user events.

The Hello class overrides the paintComponent(Graphics) method provide the code to display the applet. The paint()method is passed a Graphics object that contains the graphic context used to display the applet. The paintComponent() method calls the graphic context drawString(String, int, int) method to display the “Hello there! This is how Applets look and feel” string at a pixel offset of (65, 95) from the upper-left corner in the applet's display.

HTML Document: In order to run HelloWorldApplet, you need another program called HelloWorldJApplet.html, which is essentially a program that contains HelloWorldJApplet class. HTML stands for hypertext mark up language. HTML is the language, called scripting language, that the browser understands.

A typical HTML Document looks like this. Call this: HelloWorldApplet.html

   <html>
   <head>
   <title>Hello World Applet</title>
   </head>
   <body>
   <applet code=”HelloWorldApplet” width=”200” height=”200”>
   </applet>
   </body>
   </html>

An applet is placed in an HTML document using the <applet> HTML element. The applet tag has three attributes set: code=”HelloWorldApplet” specifies the name of the Applet class and width=”200” height=”200” sets the pixel width and height of the applet.

The host application, typically a Web browser, instantiates the HelloWorldApplet applet and creates an AppletContext for the applet. Once the applet has initialized itself, it is added to the AWT display hierarchy. The paint() method is called by the AWT whenever the display needs the applet to draw itself.

23.7.4 JApplets – Applets with Swing Components: Better Look and Feel

Java has introduced the latest Java Swing Components with class hierarchy: java->applet->Applet->JApplet. In order to get better and “feel good” features, it is better we make our Applet class to extend to JApplet instead of Applet. As most of the Applets use Window features, we need to import advanced windowing tool kit provided by Java and within package: java. awt. Swing components are provided by javax (x stands for java extended) to provide rich libraries so that GUI/Interfaces, etc., are easily implemented.

We can clearly see in Figure 23.19 that JApplet extends Panel that in turn extends to Container class. Therefore, we need to add components to JApplet class.

 

Class hierarchy of JApplet class

 

Figure 23.19 Class hierarchy of JApplet class

 

Example 23.17:   HelloWorldJApplet.java: Java Applet with Swing

import javax.swing.*;
import java.awt.*;
public class HelloWorldJApplet extends JApplet {
public void init() {
//First Get Container object
Container myContentPane=getContentPane();
// we have set the layout. we will use flow layout
myContentPane.setLayout(new FlowLayout());
//Prepare the lable to post on myContentPane
JLabel message = new JLabel(“Welcome to swing components in Java”);
//add label to myContentpane
myContentPane.add(message);
}
}
Line No. 7: defines an object of Container class called myContentpane. getContentPane() returns object of Container.
Line No. 9: is setting the layout to FlowLayou()
Line No. 11: creates an object of JLabel and passes a Tring for display.
Line No 13: Just adds message to Container.

To obtain the output, compile the program to get HelloWorld.class. If you are using eclipse IDE you can directly execute the program to get the output. Or create an HTML document as explained in the previous section. The output is shown in Figure 23.20.

 

JApplet output

 

Figure 23.20 JApplet output

 

Example 23.18:   HelloWorldJApplet.html: Html Script for HelloWorldJApplet.java

<html>
<title>HelloWorldJApplet</title>
<body>
  <applet code=”HelloWorldJApplet.class”
  width=400 height = 200>
 </applet>
</body>
</html>

Create the above program by name HelloWorldJApplet.html in the directory c:oopsjavaworkspaceoopstech2srccomoopschap23 or any other directory you have been working. appletviewer.exe is the program supplied by java to test applets. C:Oopsjavaexamplesin> appletviewer HelloWorldJApplet.java will produce the output shown above. Alternatively, you can also create separate html file and use web browser like IE to get the same output by simply double clicking on HelloWorldJApplet.html file to invoke the web browser.

The import statements direct the Java compiler to include the javax.swing.JApplet and java.Graphics.* As JApplet classes use extensively the features of windows, we also need to import a package called awt.

The Hello class extends JApplet class; the JApplet class provides the framework for the host application to display and control the lifecycle of the applet. The JApplet class provides the applet with the capability to display GUI and respond to user events.

Which is better Applet or JApplet in terms of look and feel? Refer to Figures 23.18 and 23.20. You will agree that applets with swing components offer much better look and feel. Hence we will use swing components with Applets. From now on we will not be writing HTML Tags. It is understood that you will be able to understand and execute your applet programs.

23.7.5 Applets vs. Stand-alone Applications

Stand-Alone Applications

The programs we did so far are called stand-alone programs. The signature of stand-alone applications is that it will have a main() method. Stand-alone application in java is similar to application development using c++ and contains all features of language.

Applets

  • Applets are run by web browsers. They are designed to work on the Internet.
  • The signature of applet is that it will not have main() methods. Instead it will have init() methods.
  • Applets cannot be run independently. They need to be embedded into HTML tags. HTML stands for Hyper Text Mark Up Language.
  • Due to security restrictions, applets cannot read form local files/disks or write to a disk.
  • Applets do not have any access to any other programs residing in local computers.

23.7.6 Passing Arguments to Applets

The applet tag we have used to embed out class in HTML tags is shown below:

    <applet code=”HelloWorldApplet” width=”200” height=”200”> </applet>. This is a simple tag. We will now introduce you to a full-fledged HTML file.

 

Example 23.19:   An Example HTML Full Fledged File

    <APPLET
    [CODEBASE = codebase_URL] // directory of html file
    CODE= “Applet class name” // for example ”HelloWorldJApplet.class”
    [ ALT = alternate_text]
    [ NAME = applet _instance_name]
    WIDTH=no of pixels
    HEIGHT = no of pixels
    [ ALLIGN = alignment] //TOP BOTTOM, LEFT,RIGHT,MIDDLE etc
    [VSPACE]= pixels] // used when align LEFT or RIGHT is used
    [HSPACE]=pixels] //used when TOP or BOTTOM are used
  >
  [PARAM NAME = name1 VALUE = value1> ] // used for parameters passing
  [PARAM NAME = name2 VALUE = value2> ]
  </APPLET>

Let us attempt an example wherein we pass arguments to applet. We will pass colour and text to be displayed by the applet. In addition, we will pass two numbers and operations to be performed by the applet. Let us see the result.

 

Example 23.20:   Write a Swing-based Applet to Accept String Value as Parameter From Html Tag File. The Program to Display Hello India! If There is Input India From the Tag File. Else it Has to Display Hello Delhi!

   //: HTMLParam.java
   1. /*<HTML><BODY><Applet Code=”HTMLParam.class”
   2. width=400 height =200> <PARAM NAME = “String”VALUE= “India!” >
   3. </Applet></BODY></HTML> */
   4. import javax.swing.*;
   5. import java.awt.*;
   6. public class HTMLParam extends JApplet {
   7. String stg;
   8. public void init() {
   9. //Get the String to be displayed
   10. stg=getParameter(“String”);
   11. if ( stg==null)
   12. stg=”Delhi!”;
   13. stg=”Hello “+stg;
   14. //First Get Container object
   15. Container myContentPane=getContentPane();
   16. // we have set the layout. we will use flow layout
   17. myContentPane.setLayout(new FlowLayout());
   18. //Prepare the lable to post on myContentPane
   19. JLabel message = new JLabel(stg);
   20. //add label to myContentpane
   21. myContentPane.add(message);
   22. }
   23. }

 

image

 

Example 23.22:   InputToApplet.java A Program to Accept Bank Account and Transaction Amount and Applet Will Return Bank Balance After Transaction

   /*<HTML><BODY><Applet Code=”InputToApplet.class” width=800 height =800></Applet></BODY></HTML> */
   1. package com.oops.chap23;
   2. import javax.swing.*;
   3. import java.awt.*;
   4. import java.awt.event.*;// for action listener interface
   5. public class SwingInputs extends JApplet{
   6. public void init() {
   7. //First Get Container object
   8. Container myContentPane=getContentPane();
   9. // we have set the layout. we will use flow layout
   10.   myContentPane.setLayout(new GridLayout(1,1));
   11.  //Prepare the lable to post on myContentPane
   12.    JPanel panel = new SwingPanel();
   13.    myContentPane.add(panel);
   14.    }
   15.    }
   16.    class SwingPanel extends JPanel implements ActionListener{
   17.    String val1,val2,stg;
   18.    double bal=20000.00;
   19.    JTextField jtf1,jtf2,jtf3;
   20.    SwingPanel(){
   21.    JLabel label =new JLabel(“Enter accountNo :”);
   22.    add(label);
   23.    jtf1=new JTextField(10);
   24.    jtf1.addActionListener(this);
   25.    add(jtf1); // converts jtf1 to component
   26.    setLocation(100,100);
   27.    label =new JLabel(“Enter Transaction Amount : “);add(label);
   28.    jtf2=new JTextField(10);
   29.    jtf2.addActionListener(this);
   30.    add(jtf2);
   31.    label =new JLabel(“
Bank Balance “);add(label);
   32.    jtf3=new JTextField(10);
   33.    stg=String.valueOf(bal);
   34.    jtf3.setText(stg);
   35.    add(jtf3);
   36.    label = new JLabel(“Have a Great Day ahead!”);
   37.    add(label);
   38.    }
   39.    public void actionPerformed(ActionEvent e){
   40.    int acn=Integer.parseInt(jtf1.getText());
   41.    double amt=Double.parseDouble(jtf2.getText());
   42.    double banbal=bal-amt;
   43.    String stg=String.valueOf(banbal);
   44.    jtf3.setText(stg);
   45.    }
   46.    }

Line No. 4:

imports java.awt.event.*;// for action listener interface

Line No. 8:

defines myContentpane as object of Container.

Line No. 12:

defines a JPanel object called panel. We can add components now to this panel.

Line No. 16:

class SwingPanel extends JPanel implements ActionListener{ Implements action listeners for attaching action listeners events to widgets inside the class.

Line No. 19:

declares three JText fields ; JTextField jtf1,jtf2,jtf3;

Line No. 20:

is a constructor SwingPanel. Line No. 21 to 38 are used to define the text fields and attach action Listeners by using the method addActionListeners like jtf1.addActionListener(this); at Line No. 23.

Line No. 39: defines a mandatory method called public void action Performed(ActionEvent e){
Line Nos. 40 & 41: int acn=Integer.parseInt(jtf1.getText()); double amt=Double.parseDouble(jtf2.getText()); are used to get the text in String format and convert them to basic data type using parseInt and parseDouble.
Line No. 42: displays the amount by converting basic data type to String type . It uses valueOf() method

 

image

23.8 Summary

  1. Graphical User Interface (GUI) development in JAVA is based on components. Java components can further be divided into containers and widgets.
  2. Containers are further classified as Root Containers and Intermediate Containers.
  3. Containers also called as Top level containers are necessary for every GUI program. Examples are three top-level containers: JFrame, JDialog and JApplet.
  4. Intermediate containers are not mandatory but are used widely as they help in managing and organizing widgets. JPanel is the most widely used intermediate container in Swing.
  5. Widgets are GUI elements which are used to interact with the user. Widgets are also used to get user inputs. JButton, JLabel, JScrollBar and JCheckBox are examples of widgets in Swing.
  6. For Swing Applications, the root is always JFrame.
  7. Panels are intermediate containers and as such not essential for creating Java graphical user interface programs.
  8. Widgets are the components which help us to build user interfaces. They are the components that the user actually sees and interacts with users.
  9. The JLabel object is used to display text, images or both text and images in Java.
  10. The JButton object is used to display buttons in Java. Buttons are very useful user interface elements, which can be used for a variety of user interactions.
  11. The JCheckBox object is used to display checkboxes in Java. Checkboxes allow users to either select or deselect an item; they also allow multiple items to be selected at the same time.
  12. The JComboBox in Java has a button and a drop-down list.
  13. Menus in Java are implemented using three components, namely, JMenuBar, JMenu and JMenuItems.
  14. Border layout divides the panel into five regions North, South, East, West and Center, as shown below.
  15. Grid Layout divides the screen into specified rows and columns. Grid layout is useful when we want to create UI similar to windows desktop wherein icon is symmetrically placed in the screen.
  16. Flow layout is the default layout. If you do not specify any layout using the setLayout() method, then by default the panel will have Flow layout. In flow layout, the widgets are arranged from left to right and then from top to bottom.
  17. Events are generated due to user activity and they can range from key presses, mouse clicks, to selecting/deselecting checkboxes and button clicks.
  18. Toolkit (AWT) framework is responsible for delivering user-generated events to the applications. AWT also defines the interfaces for all the event handlers.
  19. Events in Java can be classified into two types: high-level events and low-level events.
  20. High-level events such as Action events are specific to certain widgets and are sent to the application only if those widgets are present and have registered for the event.
  21. Low-level events such as Keyboard and Mouse events are sent to all the widgets which have registered to receive them.
  22. Action events are generated whenever the user performs any action on the widget like pressing a button or choosing an item from the menu.
  23. To enable us to handle action events, we need to create a class that implements the ActionListener interface. The ActionListener interface requires us to implement just one method actionPerformed(ActionEvent e).
  24. Item events are generally fired by components such as checkboxes, radio buttons and combo boxes wherein the user selects or deselects an item.
  25. ItemListener interface requires us to implement one method itemStateChanged (ItemEvent e).
  26. Key events are generated whenever the user presses and releases keys on the Keyboard. The events are: keyPressed(KeyEvent key): keyReleased(KeyEvent key): keyTyped(KeyEvent key).
  27. Mouse events like the key events are low-level events. They are mouseEntered (MouseEvent e): mouseExited(MouseEvent e): mousePressed(MouseEvent e): mouseReleased(MouseEvent e): mouseClicked(MouseEvent e).
  28. Applets are small java programs that are transported from one computer system on the network to another system. They cannot be run independently but they need web browser or program called appletviewer to run on the system.
  29. Applet class hierarchy is: java->applet->Applet. So the applet class must extend to package java.applet.Applet.
  30. When applets are loaded web browser automatically calls the methods init(),Start() : Stop() : Destroy():Paint(Graphics g) : Update(Graphics g).
  31. Java has introduced the latest Java Swing Components with class hierarchy: java->applet->Applet->JApplet. In order to get better and “feel good” features.
  32. Applets cannot be run independently. They need to be embedded into HTML tags. HTML stands for Hyper Text Mark Up Language.
  33. Due to security restrictions, applets cannot read from local files/disks or write to a disk. Applets do not have any access to any other programs residing on local computers.
  34. When local disks need to be handled, applications supported by JFrame provide excellent graphics facilities.

Exercise Questions

Objective Questions

  1. Which component is not part of root containers?
    1. JDialog
    2. JApplet
    3. JFrame
    4. JPanel
  2. Which of the following are not part of widgets?
    1. JPanel
    2. JButton
    3. JTextField
    4. JMenu
  3. JFrame is a
    1. Top-level container
    2. Intermediate container
    3. A widget
    4. Component
  4. Which of the following are not mandatory?
    1. top-level container
    2. intermediate
    3. widget
    4. components
  5. Which of the following are offered by JFrame?
    1. title
    2. icon
    3. set height width and location
    4. add widgets directly
    1. i and ii
    2. ii, iii and iv
    3. i, ii, iii and iv
    4. i, ii and iii
  6. JPanel is a container belonging to
    1. top level
    2. bottom level
    3. widget
    4. intermediate level
  7. The component used for displaying the text in a window
    1. JPanel
    2. JLabel
    3. JTextField
    4. JFrame
  8. The layout to be used when we need rows and columns on screen is a
    1. Flow layout
    2. Grid layout
    3. Border layout
    4. Matrix layout
  9. Action Listeners needs actionPerformed() method to be executed.

    TRUE/FALSE

  10. ItemListener requires the following method to be implemented:
    1. itemStateChanged(ItemEvent e)
    2. addActionListener(new HandleEvent())
    3. actionPerformed(ActionEvent e)
    4. getItemSelectable( )

    Short-answer Questions

  11. What are the two packages required to do multimedia programming in java?
  12. What are high-level containers?
  13. What are widgets?
  14. What are intermediate containers?
  15. Distinguish Applet and JApplets.
  16. Distinguish Action Listeners and Item Listeners?
  17. Explain the states of n Applet.
  18. Explain Applet Tag and mandatory tags.
  19. Explain how parameters are passed to Applet through HTML files.
  20. Distinguish Applets and Stand-alone applications.

    Long-answer Questions

  21. Distinguish between Component and Container.
  22. Explain the class hierarchy of Applet and JApplet.
  23. Explain the methods in Keyboard event listeners.
  24. Explain the methods in Mouse Event listeners.
  25. Explain how an applet program can be converted into application Program.

    Assignment Questions

  26. Develop an application program with swing components for recording of students results on a remote computer (Server). The data obtained through a form needs to be submitted online for the server to record it on to its random file.
  27. Modify the above program so that a student can submit his roll number and he is informed about his result. Use Applet with swing components for developing interface.
  28. Develop an interface wherein a customer can select his choice of items in a restaurant using JCheckBoxes and a Button and he is informed of the cost of his selection.
  29. Write a program to implement calculator with basic arithmetic operation.
  30. Write a multithreaded Applet for analog clock second, minutes and hour handles.

Solutions to Objective Questions

  1. d
  2. a
  3. a
  4. b
  5. c
  6. d
  7. c
  8. b
  9. True
  10. a

16. b

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.72.176