Concept Of Window and Advanced Components In Java

techgeek.in's Avatar author of Concept Of Window and Advanced Components In Java
This is an article on Concept Of Window and Advanced Components In Java in Java.
In this article I will discuss about window and some advanced components which can be added to our window such as Menu Bars and Menus.

Window Fundamentals



The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level. The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard window. Much of the functionality of these windows is derived from their parent classes.

Component



At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font.

Container



The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains.

Panel



The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements Container. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. APanel is a window that does not contain a title bar, menu bar, or border. When you run an applet using an applet viewer, the applet viewer provides the title and border. Other components can be added to a Panel object by its add( ) method inherited from Container. Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component.

Window



The Window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, we don’t create

Window objects directly. Instead, we use a subclass of Window called Frame.

Frame



Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.

Canvas



It is not part of the hierarchy for applet or frame windows. Canvas encapsulates a blank window upon which you can draw.

Working with Frame Windows



After the applet, the type of window you will most often create is derived from Frame.

We will use it to create child windows within applets, and top-level or child windows for applications. It creates a standard-style window.

Frame’s constructors are as follows:
  1. Frame( )
  2. Frame(String title)

The first form creates a standard window that does not contain a title.

The second form creates a window with the title specified by title. We cannot specify the dimensions of the window. We must set the size of the window after it has been created. Some of the methods used when working with windows are as follows:

Setting the Window’s Dimensions

The setSize( ) method is used to set the dimensions of the window.

Its signature is shown here:
  1. void setSize(int newWidth, int newHeight)
  2. void setSize(Dimension newSize)

The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels.

The getSize( ) method is used to obtain the current size of a window.

Its signature is shown here:

Dimension getSize( )

This method returns the current size of the window contained within the width and height fields of a Dimension object.

Hiding and Showing a Window

After a frame window has been created, it will not be visible until you call setVisible( ). Its signature is shown here:

void setVisible(boolean visibleFlag)

The component is visible if the argument to this method is true. Otherwise, it is hidden.

Setting a Window’s Title

You can change the title in a frame window using setTitle( ).

Its signature is shown here:

void setTitle(String newTitle)

Here, newTitle is the new title for the window.

Closing a Frame Window

When using a frame window, your program must remove that window from the screen when it is closed, by calling setVisible(false). To intercept a window-close event, you must implement the windowClosing( ) method of the WindowListener interface. Inside windowClosing( ), you must remove the window from the screen.

Creating a Frame Window in an Applet



While it is possible to simply create a window by creating an instance of Frame, we will seldom do so, because we will not be able to do much with it. For example, we will not be able to receive or process events that occur within it or easily output information to it. Most of the time, we will create a subclass of Frame. Doing so lets you override Frame’s methods and event handling.

Creating a new frame window from within an applet is quite easy. First, create a subclass of Frame. Next, override any of the standard window methods, such as init( ), start( ), stop( ), and paint( ). Finally, implement the windowClosing( ) method of the WindowListener interface, calling setVisible(false) when the window is closed. Once we have defined a Frame subclass, we can create an object of that class. This causes a frame window to come into existence, but it will not be initially visible. We make it visible by calling setVisible( ). When created, the window is given a default height and width. We can set the size of the window explicitly by calling the setSize( ) method.

The following applet creates a subclass of Frame called SampleFrame. A window of this subclass is instantiated within the init( ) method of AppletFrame. Notice that SampleFrame calls Frame’s constructor. This causes a standard frame window to be created with the title passed in title. This example overrides the applet window’s start( ) and stop( ) methods so that they show and hide the child window, respectively.

This causes the window to be removed automatically when we terminate the applet, when we close the window, or, if using a browser, when we move to another page. It also causes the child window to be shown when the browser returns to the applet.

Code:
// Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
// Create a subclass of Frame.
class SampleFrame extends Frame 
  {
     SampleFrame(String title) 
        {
            super(title);
            // create an object to handle window events
            MyWindowAdapter A = new MyWindowAdapter(this);
            // register it to receive those events
            addWindowListener(A);
        }
      public void paint(Graphics g) 
        {
             g.drawString("This is in frame window", 10, 40);
        }
  }

class MyWindowAdapter extends WindowAdapter 
  {
      SampleFrame s; 
      public MyWindowAdapter(SampleFrame sampleFrame) 
         {
             s= sampleFrame;
          }
      public void windowClosing(WindowEvent we) 
          {
             s.setVisible(false);
           }
   }
// Create frame window.
 public class AppletFrame extends Applet 
    { 
             Frame f;
             public void init() 
               {
                  f = new SampleFrame("A Frame Window");
                  f.setSize(250, 250);
                  f.setVisible(true);
               } 
             public void start() 
               {
                  f.setVisible(true);
               }
             public void stop() 
               {
                  f.setVisible(false);
                }
             public void paint(Graphics g) 
               {
                  g.drawString("This is in applet window", 10, 20);
               }
  }
Sample output from this program is shown here:



Menu Bars and Menus



A top-level window can have a menu bar associated with it. A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-down menu. This concept is implemented in Java by the following classes: MenuBar, Menu, and MenuItem.

In general, a menu bar contains one or more Menu objects. Each Menu object contains a list of MenuItem objects. Each MenuItem object represents something that can be selected by the user. Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be created. It is also possible to include checkable menu items. These are menu options of type CheckboxMenuItem and will have a check mark next to them when they are selected.

To create a menu bar, first create an instance of MenuBar. This class only defines the default constructor. Next, create instances of Menu that will define the selections displayed on the bar.

Following are the constructors for Menu:
  1. Menu( )
  2. Menu(String optionName)
  3. Menu(String optionName, boolean removable)

Here, optionName specifies the name of the menu selection. If removable is true, the pop-up menu can be removed and allowed to float free. Otherwise, it will remain attached to the menu bar.

The first form creates an empty menu.

Individual menu items are of type MenuItem. It defines these constructors:
  1. MenuItem( )
  2. MenuItem(String itemName)
  3. MenuItem(String itemName, MenuShortcut keyAccel)

Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut for this item. You can disable or enable a menu item by using the setEnabled( ) method.

Its form is shown here:

void setEnabled(boolean enabledFlag)

If the argument enabledFlag is true, the menu item is enabled. If false, the menu item is disabled.

You can determine an item’s status by calling isEnabled( ).

This method is shown here:

boolean isEnabled( )

isEnabled( ) returns true if the menu item on which it is called is enabled. Otherwise, it returns false.

You can change the name of a menu item by calling setLabel( ). You can retrieve the current name by using getLabel( ).

These methods are as follows:

void setLabel(String newName)
String getLabel( )


Here, newName becomes the new name of the invoking menu item. getLabel( ) returns the current name.

You can create a checkable menu item by using a subclass of MenuItem called CheckboxMenuItem.

It has these constructors:
  1. CheckboxMenuItem( )
  2. CheckboxMenuItem(String itemName)
  3. CheckboxMenuItem(String itemName, boolean on)

Here, itemName is the name shown in the menu. Checkable items operate as toggles. Each time one is selected, its state changes. In the first two forms, the checkable entry is unchecked.

In the third form, if on is true, the checkable entry is initially checked. Otherwise, it is cleared.

You can obtain the status of a checkable item by calling getState( ). You can set it to a known state by using setState( ).

These methods are shown here:
  1. boolean getState( )
  2. void setState(boolean checked)
If the item is checked, getState( ) returns true. Otherwise, it returns false. To check an item, pass true to setState( ). To clear an item, pass false.

Once you have created a menu item, you must add the item to a Menu object by using add( ), which has the following general form:

MenuItem add(MenuItem item)

Here, item is the item being added. Items are added to a menu in the order in which the calls to add( ) take place. The item is returned.

Once you have added all items to a Menu object, you can add that object to the menu bar by using this version of add( ) defined by MenuBar:

Menu add(Menu menu)

Here, menu is the menu being added. The menu is returned.

Menus only generate events when an item of type MenuItem or CheckboxMenuItem is selected. They do not generate events when a menu bar is accessed to display a drop-down menu, for example. Each time a menu item is selected, an ActionEvent object is generated. Each time a check box menu item is checked or unchecked, an ItemEvent object is generated. Thus, you must implement the ActionListener and ItemListener interfaces in order to handle these menu events.

The getItem( ) method of ItemEvent returns a reference to the item that generated this event.

The general form of this method is shown here:

Object getItem()

Code:
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MenuDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Frame
class MenuF extends Frame 
  {
      String msg = "";
      CheckboxMenuItem debug,test;
      MenuF(String title) 
        {
          super(title);
          // create menu bar and add it to frame
          MenuBar MB = new MenuBar();
          setMenuBar(MB);
          // create the menu items
          Menu F= new Menu("File");
          MenuItem I1,I2,I3,I4,I5;
          F.add(I1 = new MenuItem("New..."));
          F.add(I2 = new MenuItem("Open..."));
          F.add(I3 = new MenuItem("Close"));
          F.add(I4 = new MenuItem("-"));
          F.add(I5 = new MenuItem("Quit..."));
          MB.add(F);
          Menu E = new Menu("Edit");
          MenuItem I6,I7,I8,I9;
          E.add(I6 = new MenuItem("Cut"));
          E.add(I7 = new MenuItem("Copy"));
          E.add(I8 = new MenuItem("Paste"));
          E.add(I9 = new MenuItem("-"));
          Menu S= new Menu("Special");
          MenuItem I10, I11, I12;
          S.add(I10 = new MenuItem("First"));
          S.add(I11 = new MenuItem("Second"));
          S.add(I12 = new MenuItem("Third"));
          E.add(S);
          // these are checkable menu items
          debug = new CheckboxMenuItem("Debug");
          E.add(debug);
          test = new CheckboxMenuItem("Testing");
          E.add(test);
          MB.add(E);
          // create an object to handle action and item events
          MyMenuHandler handler = new MyMenuHandler(this);
          // register it to receive those events
          I1.addActionListener(handler);
          I2.addActionListener(handler);
          I3.addActionListener(handler);
          I4.addActionListener(handler);
          I5.addActionListener(handler);
          I6.addActionListener(handler);
          I7.addActionListener(handler);
          I8.addActionListener(handler);
          I9.addActionListener(handler);
          I10.addActionListener(handler);
          I11.addActionListener(handler);
          I12.addActionListener(handler);
          debug.addItemListener(handler);
          test.addItemListener(handler);
          // create an object to handle window events
          MyWindowAdapter adapter = new MyWindowAdapter(this);
          // register it to receive those events

          addWindowListener(adapter);
        }

      public void paint(Graphics g) 
        {
          g.drawString(msg, 10, 200);
          if(debug.getState())
          g.drawString("Debug is on.", 10, 220);
          else
          g.drawString("Debug is off.", 10, 220);
          if(test.getState())
          g.drawString("Testing is on.", 10, 240);
          else
          g.drawString("Testing is off.", 10, 240);
        }
  }


class MyWindowAdapter extends WindowAdapter 
   {
       MenuF MF;
       public MyWindowAdapter(MenuF menuFrame) 
         {
           MF = menuFrame;
         }

       public void windowClosing(WindowEvent we) 
         {
           MF.setVisible(false);
         }
   }

class MyMenuHandler implements ActionListener, ItemListener 
   {
      MenuF MF;
      public MyMenuHandler(MenuF menuFrame) 
        {
          MF = menuFrame;
        }
      // Handle action events
      public void actionPerformed(ActionEvent ae) 
        {
          String msg = "You selected ";
          String arg = (String)ae.getActionCommand();
          if(arg.equals("New..."))
          msg += "New.";
          else if(arg.equals("Open..."))
          msg += "Open.";
          else if(arg.equals("Close"))
          msg += "Close.";
          else if(arg.equals("Quit..."))
          msg += "Quit.";
          else if(arg.equals("Edit"))
          msg += "Edit.";
          else if(arg.equals("Cut"))
          msg += "Cut.";
          else if(arg.equals("Copy")) 
          msg += "Copy.";
          else if(arg.equals("Paste"))
          msg += "Paste.";
          else if(arg.equals("First"))
          msg += "First.";
          else if(arg.equals("Second"))
          msg += "Second.";
          else if(arg.equals("Third"))
          msg += "Third.";
          else if(arg.equals("Debug")) 
          msg += "Debug.";
          else if(arg.equals("Testing"))
          msg += "Testing.";
          MF.msg = msg;
          MF.repaint();
        }
      // Handle item events

      public void itemStateChanged(ItemEvent ie) 
        {
          MF.repaint();
        }
   }
  // Create frame window.

public class MenuDemo extends Applet 
   {
     Frame f;
     public void init() 
       {
         f = new MenuF("Menu Demo");
         int w= Integer.parseInt(getParameter("width"));
         int h= Integer.parseInt(getParameter("height"));
         setSize(new Dimension(w,h));
         f.setSize(w,h);
         f.setVisible(true);
       }
     public void start() 
       {
         f.setVisible(true);
       }
     public void stop() 
       {
         f.setVisible(false);
       }
   }
Sample output from the MenuDemo applet is as shown below:



There is one other menu-related class that you might find interesting: PopupMenu. It works just like Menu but produces a menu that can be displayed at a specific location. PopupMenu provides a flexible, useful alternative for some types of menuing situations.

Dialog Boxes



Often, you will want to use a dialog box to hold a set of related controls. Dialog boxes are primarily used to obtain user input. They are similar to frame windows, except that dialog boxes are always child windows of a top-level window. Also, dialog boxes don’t have menu bars. In other respects, dialog boxes function like frame windows. You can add controls to them, in the same way that you add controls to a frame window. Dialog boxes may be modal or modeless. When a modal dialog box is active, all input is directed to it until it is closed. This means that you cannot access other parts of your program until you have closed the dialog box. When a modeless dialog box is active, input focus can be directed to another window in your program. Thus, other parts of your program remain active and accessible.

Dialog boxes are of type Dialog.

Two commonly used constructors are shown here:
  1. Dialog(Frame parentWindow, boolean mode)
  2. Dialog(Frame parentWindow, String title, boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal. Otherwise, it is modeless. The title of the dialog box can be passed in title. Generally, you will subclass Dialog, adding the functionality required by your application.

Example:

Following is a modified version of the preceding menu program that displays a modeless dialog box when the New option is chosen. Notice that when the dialog box is closed, dispose( ) is called. This method is defined by Window, and it frees all system resources associated with the dialog box window.

Code:
// Demonstrate Dialog box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="DialogDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Dialog.
class SampleDialog extends Dialog implements ActionListener 
   {
     SampleDialog(Frame parent, String title) 
       {
         super(parent, title, false);
         setLayout(new FlowLayout());
         setSize(300, 200);
         add(new Label("Press this button:"));
         Button b;
         add(b = new Button("Cancel"));
         b.addActionListener(this);
       }

     public void actionPerformed(ActionEvent ae) 
       {
         dispose();
       }

     public void paint(Graphics g) 
       {
         g.drawString("This is in the dialog box", 10, 70);
       }
   }
     // Create a subclass of Frame.

class MenuF extends Frame 
   {
     String msg = "";
     CheckboxMenuItem debug, test;
     MenuF(String title) 
      {
        super(title);
        // create menu bar and add it to frame 
        MenuBar MB= new MenuBar();
        setMenuBar(MB);
        // create the menu items
        Menu F = new Menu("File");
        MenuItem I1,I2,I3,I4;
        F.add(I1 = new MenuItem("New..."));
        F.add(I2 = new MenuItem("Open..."));
        F.add(I3 = new MenuItem("Close"));
        F.add(new MenuItem("-"));
        F.add(I4 = new MenuItem("Quit..."));
        MB.add(F);
        Menu E = new Menu("Edit");
        MenuItem I5,I6,I7;
        E.add(I5 = new MenuItem("Cut"));
        E.add(I6 = new MenuItem("Copy"));
        E.add(I7 = new MenuItem("Paste"));
        E.add(new MenuItem("-"));
        Menu S= new Menu("Special", true);
        MenuItem I8,I9,I10;
        S.add(I8 = new MenuItem("First"));
        S.add(I9 = new MenuItem("Second"));
        S.add(I10 = new MenuItem("Third"));
        E.add(S);
        // these are checkable menu items
        debug = new CheckboxMenuItem("Debug");
        E.add(debug);
        test = new CheckboxMenuItem("Testing");
        E.add(test);
        MB.add(E);
        // create an object to handle action and item events
        MyMenuHandler H = new MyMenuHandler(this); 
        // register it to receive those events
       I1.addActionListener(H);
       I2.addActionListener(H);
       I3.addActionListener(H);
       I4.addActionListener(H);
       I5.addActionListener(H);
       I6.addActionListener(H);
       I7.addActionListener(H);
       I8.addActionListener(H);
       I9.addActionListener(H);
       I10.addActionListener(H);
       debug.addItemListener(H);
       test.addItemListener(H);
       // create an object to handle window events
       MyWindowAdapter A = new MyWindowAdapter(this);
       // register it to receive those events
       addWindowListener(A);
     } 
    public void paint(Graphics g) 
     {
       g.drawString(msg, 10, 200);
       if(debug.getState())
       g.drawString("Debug is on.", 10, 220);
       else
       g.drawString("Debug is off.", 10, 220);
       if(test.getState()) 
       g.drawString("Testing is on.", 10, 240);
       else
       g.drawString("Testing is off.", 10, 240); 
     }
   }

class MyWindowAdapter extends WindowAdapter 
   {
     MenuF MF;
     public MyWindowAdapter(MenuF menuFrame) 
      {
        MF = menuFrame;
      }

     public void windowClosing(WindowEvent we) 
      {
        MF.dispose();
      }
   }

class MyMenuHandler implements ActionListener, ItemListener 
   {
     MenuF MF;
     public MyMenuHandler(MenuF menuFrame) 
      {
       MF = menuFrame;
      }
     // Handle action events
     public void actionPerformed(ActionEvent ae) 
      {
        String msg = "You selected ";
        String arg = (String)ae.getActionCommand();
        // Activate a dialog box when New is selected.
        if(arg.equals("New...")) 
          { 
           msg += "New.";
           SampleDialog d = new
           SampleDialog(MF, "New Dialog Box");
           d.setVisible(true);
          }
        // Try defining other dialog boxes for these options.
        else if(arg.equals("Open..."))
        msg += "Open.";
        else if(arg.equals("Close"))
        msg += "Close.";
        else if(arg.equals("Quit..."))
        msg += "Quit.";
        else if(arg.equals("Edit"))
        msg += "Edit.";
        else if(arg.equals("Cut"))
        msg += "Cut.";
        else if(arg.equals("Copy"))
        msg += "Copy.";
        else if(arg.equals("Paste"))
        msg += "Paste.";
        else if(arg.equals("First"))
        msg += "First.";
        else if(arg.equals("Second"))
        msg += "Second.";
        else if(arg.equals("Third"))
        msg += "Third.";
        else if(arg.equals("Debug"))
        msg += "Debug.";
        else if(arg.equals("Testing"))
        msg += "Testing.";
        MF.msg = msg;
        MF.repaint();
      }

     public void itemStateChanged(ItemEvent ie) 
      {
        MF.repaint();
      }
  }
// Create frame window.
public class DialogDemo extends Applet 
  { 
    Frame f;
    public void init() 
     {
       f = new MenuF("Menu Demo");
       int w= Integer.parseInt(getParameter("width"));
       int h= Integer.parseInt(getParameter("height"));
       setSize(w,h);
       f.setSize(w,h);
       f.setVisible(true);
     }
    public void start() 
     {
       f.setVisible(true);
     }
    public void stop() 
     {
       f.setVisible(false);
     }
   }
Here is sample output from the DialogDemo applet:



FileDialog



Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box, instantiate an object of type FileDialog. This causes a file dialog box to be displayed. Usually, this is the standard file dialog box provided by the operating system.

FileDialog provides these constructors:
  1. FileDialog(Frame parent, String boxName)
  2. FileDialog(Frame parent, String boxName, int how)
  3. FileDialog(Frame parent)
Here, parent is the owner of the dialog box, and boxName is the name displayed in the box’s title bar. If boxName is omitted, the title of the dialog box is empty. If how is FileDialog.LOAD, then the box is selecting a file for reading. If how is FileDialog.SAVE, the box is selecting a file for writing.

The third constructor creates a dialog box for selecting a file for reading. FileDialog( ) provides methods that allow you to determine the name of the file and its path as selected by the user.

Here are two of them:
  1. String getDirectory( )
  2. String getFile( )

These methods return the directory and the filename, respectively.

Example:

The following program activates the standard file dialog box:

Code:
/* demonstrate File Dialog box.
This is an application, not an applet.
*/
import java.awt.*;
import java.awt.event.*;
// Create a subclass of Frame
class SampleFrame extends Frame 
   {
     SampleFrame(String title) 
      {
        super(title);
        // create an object to handle window events
        MyWindowAdapter adapter = new MyWindowAdapter(this);
        // register it to receive those events
        addWindowListener(adapter);
      }
   }

class MyWindowAdapter extends WindowAdapter 
   {
     SampleFrame sampleFrame;
     public MyWindowAdapter(SampleFrame sampleFrame) 
      {
        this.sampleFrame = sampleFrame;
      }

     public void windowClosing(WindowEvent we) 
      {
        sampleFrame.setVisible(false);
      }
   }
// Create frame window.

class FileDialogDemo 
   {
      public static void main(String args[]) 
       { 
         Frame f = new SampleFrame("File Dialog Demo");
         f.setVisible(true);
         f.setSize(100, 100);
         FileDialog fd = new FileDialog(f, "File Dialog");
         fd.setVisible(true);
       } 
   }
The output generated by this program is shown as follows:-

prosenjit like this
0
prosenjit's Avatar, Join Date: Mar 2010
Newbie Member
thanks for this valuable informations
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
If you liked this article do nominate this article for Article of the month - May 2010