Docstoc

JAVA part-5/1

Document Sample
JAVA part-5/1 Powered By Docstoc
					UNIT-5
 Advantages of GUI over CUI
 The AWT class hierarchy- Component, Frame
 Event handling: Delegation Event model
 Closing a frame, mouse and keyboard events
 Adapter classes
 User interface components:
 Labels, button, scrollbars
 Text components, check box, check box groups, choices
 Lists panels – ScrollPane, MenuBar, graphics
 Layout manager – layout manager types
 Concepts of Applets, differences between applets and
  Applications
 Life cycle of an applet
 Types of applets, creating applets, passing parameters to applets
                Advantages of GUI over CUI
 Presents a user-friendly mechanism for interacting with an
  application.
 Built from GUI components.
 It need more resources
 Speed is less compare to the CUI



 In a Command Line Interface, the commands are entered from
  the keyboard. It is not user-friendly.
 Difficult to remember commands.
 It need less resources
 Speed is more compare to the GUI
Most modern programs use a GUI.
 Graphical: Not just text or characters but windows, menus,
  buttons, ..
 User: Person using the program
 Interface: Way to interact with the program


Graphical Elements include:
       Window                List
       Choice                Label
       Menu                  Scrollbar
       Button                TextComponent      etc.,
button           menus   title bar   menu bar   combo box




                                                            scroll
                                                            bars




         Internet Explorer Window with GUI components
               Abstract Window Toolkit (AWT)

 The AWT contains several classes and methods that allow you to
  create and manage windows.

 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.

 The main purpose of the AWT is to support applet windows.


 It can also be used to create stand-alone GUI applications.
 AWT class hierarchy
                                          Component
                              Label
         TextArea           Button

                      TextComponent
         TextField
                     List
                                              Container
                  Choice
            CheckBox
    CheckBoxGroup                                       Panel    ScrollPane
                                          Window
      Scrollbar
    Canvas
                                      Frame    Dialog   Applet
 MenuComponent


MenuItem    MenuBar

  Menu
Component:                 (java.awt)
 Component is an abstract class that encapsulates all of the attributes of a visual
  component.
 It is a super class of all user interface classes.
 A component is something that can be displayed on a two-dimensional screen
  and with which the user can interact.
 Attributes of a component include a size, a location, foreground and background
  colors, whether or not visible etc.,

Methods defined in class Component are:

    setLocation(int, int), getLocation()    ---To set and get component location
      setSize(int, int), getSize()          ---To set and get component size
      setVisible()                          ---To show or hide the component
      setForeground(Color), getForeground() ---To set and get foreground colors
      setBackground(Color), getBackground() ---To set and get background colors
 Container:                 (java.awt)

 Container class is a subclass of Component class.
 This is a type of component that can nest other components within it.
  Ex:- Window, Frame, and panel are examples of containers.
 A Container is responsible for laying out (that is, positioning) any components
  that it contains.

Methods defined in a class Container are:

    setLayout(LayoutManager)          ---To set layout manager for display.
    add( Component )                  ---To add component to the display.
    remove( Component )               ---To remove component from display.
Panel:            (java.awt)
 The Panel class is a concrete subclass of Container class.


 A panel is a window that does not contain a title bar, or border.


 It provides space in which an application can attach any other component,
  including other panels.

 It is the superclass for Applet.


 Other components can be added to a Panel object by its add() method.


 The default layout manager for a panel is the FlowLayout layout manager.
Window:         (java.awt)
  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 won’t create Window objects directly. Instead, we use a
   subclass of Window called Frame.
Frame:          (java.awt)
  It is a type of Window with a title bar, menu bar , borders, and resizing
   corners.

 Methods defined in a Frame class are:

    setTitle(String), getTitle()         ---To set or get title
    setMenuBar(MenuBar)                  ---To set menu bar for window

Layout Manager:
  A manager is used to position and place components in a Container.
Event Handling
                  The Delegation Event Model
 It defines standard and consistent mechanisms to generate and process events.


 In this model, a source generates an event and sends it to one or more
  listeners.

 The listener simply waits until it receives an event. Once received, the listener
  processes the event and then returns.

 Listeners are created by implementing one or more of the interfaces defined
  by the java.awt.event package.

 When an event occurs, the event source invokes the appropriate method
  defined by the listener and provides an event object as its argument.

 In the delegation event model, listeners must register with a source in order
  to receive an event notification.
The Delegation Event Model        Action Events on Buttons
        Event Object
                                          ActionEvent




Event source    Event listener   Button           ActionListener
               (Event handling              (actionPerformed(…))
                  methods)
Example 1:


class MyActionListener implements ActionListener {
       //Registration Method
       source.addActionListener(this);
       public void actionPerformed(ActionEvent ae){
               // Handler_ code
       }
}
Example 2:

  class MyMouseListener implements MouseListener{
        //Registration Method
        addMouseListener(this);
        public void mouseClicked(MouseEvent me){
                 // Handler_ code
        }
        public void mouseEntered(MouseEvent me){
                 // Handler_ code
        }
        public void mouseExited(MouseEvent me){
                 // Handler_ code
        }
        public void mousePressed(MouseEvent me){
                 // Handler_ code
        }
        public void mouseReleased(MouseEvent me){
                 // Handler_ code }
        }
  }
 Events
 Events are supported by the java.awt.event package.

 An event is an object that describes a state change in a source.

 Events can be generated as a consequence of a person interacting
  with elements in a graphical user interface.

 Events may also occur that are not directly caused by interactions
  with a user interface.
  For example, an event may be generated
    when a timer expires,
     a counter exceeds a value,
    a software or hardware failure occurs.
Event Sources
 A source is an object that generates an event. This occurs when the internal
  state of that object changes in some way.

 Sources may generate more than one type of event.


 A source must register listeners in order for the listeners to receive
  notifications about a specific type of event.

 Each type of event has its own registration method.
  Here is the general form:
        public void addTypeListener(TypeListener el)
  Here, Type is the name of the event and el is a reference to the event listener.

  For example, the method that registers a keyboard event listener is called
  addKeyListener( ).
Event Listeners
 A listener is an object that is notified when an event occurs.


 It has two major requirements.
  First, it must have been registered with one or more sources to receive
  notifications about specific types of events.

  Second, it must implement methods to receive and process these
  notifications.

 For example, the MouseMotionListener interface defines two methods to
  receive notifications when the mouse is dragged or moved.

 Any object may receive and process one or both of these events if it provides
  an implementation of this interface.
Event Classes
 EventObject is a superclass of all events which is defined in java.util package.


 AWTEvent is a superclass of all AWT events that are handled by the delegation
  event model which is defined in java.awt package.

The following are the main event classes in java.awt.event package.
  Event Class                                Description
ActionEvent      Generated when a button is pressed, a list item is double-clicked,
                 or a menu item is selected.

MouseEvent        Generated when the mouse is dragged, moved, clicked, pressed,
                  or released; also generated when the mouse enters or exits
                  a component.

KeyEvent          Generated when the key is pressed , key is released, or key is
                  typed.
  Event Class                                Description

TextEvent         Generated when the value of a text area or text field is
                  changed.

MouseWheelEvent   Generated when the mouse wheel is moved.

WindowEvent       Generated when a window is activated, deactivated,
                  deiconified, iconified, opened, closing, closed.

ItemEvent         Generated when a check box or list item is clicked; also
                  occurs when a choice selection is made or a checkable
                  menu item is selected or deselected.

FocusEvent        Generated when a component gains or loses keyboard
                  focus.

AdjustmentEvent   Generated when a scroll bar is manipulated.

ContainerEvent    Generated when a component is added to or removed
                  from a container.
The ActionEvent Class
   You can obtain the command name for the invoking ActionEvent object by using the
    String getActionCommand() method.
   The getWhen( ) returns the time at which the event took place.
The KeyEvent Class
   int getKeyChar( ) which returns the character that was entered, and int getKeyCode( )
    which returns the key code.
   It defines many integer constants:
        VK_ENTER             VK_ESCAPE             VK_CANCEL    VK_UP
        VK_DOWN              VK_LEFT               VK_RIGHT     VK_PAGE_DOWN
        VK_PAGE_UP           VK_SHIFT              VK_ALT VK_CONTROL
The MouseEvent Class
   int getX( )                          int getY( )
   The int getClickCount( ) method obtains the number of mouse clicks for this event.


The ItemEvent Class
   The int getStateChange() method returns the state change (i.e., SELECTED or
    DESELECTED) for the event.
   The Object getItem( ) method can be used to obtain a reference to the item that
    generated an event.
Sources of Events
 The following table lists some of the user interface components that can generate
  the events.

  Event Source                              Description
  Button                  Generates action events when the button is pressed.

  Choice                  Generates item events when the choice is changed.

  List                    Generates action events when an item is double-
                          clicked; generates item events when an item is
                          selected or deselected.

   Window                 Generates window events when a window is activated,
                          closed, deactivated, deiconified, iconified, opened, or
                          quit.
Event Source                        Description

Menu Item         Generates action events when a menu item is
                  selected; generates item events when a checkable
                  menu item is selected or deselected.

Scrollbar         Generates adjustment events when the scroll bar is
                  manipulated.

Text components   Generates text events when the user enters a character.



Checkbox          Generates item events when the check box is
                  selected or deselected.
Listener Interfaces
    Interface                     Description
  ActionListener       Defines one method to receive action events.


  AdjustmentListener   Defines one method to receive adjustment events.


  ComponentListener    Defines four methods to recognize when a component is
                       hidden, moved, resized, or shown.


  ContainerListener    Defines two methods to recognize when a component is
                       added to or removed from a container.


  FocusListener        Defines two methods to recognize when a component
                       gains or loses keyboard focus.


  ItemListener         Defines one method to recognize when the state of an
                       item changes.


  KeyListener          Defines three methods to recognize when a key is pressed,
                       released, or typed.
 Interface                     Description                     Contd…
MouseListener         Defines five methods to recognize when the
                      mouse is clicked, enters a component, exits a
                      component, is pressed, or is released.


MouseMotionListener   Defines two methods to recognize when the
                      mouse is dragged or moved.


MouseWheelListener    Defines one method to recognize when the
                      mouse wheel is moved.


TextListener          Defines one method to recognize when a text
                      value changes.


WindowFocusListener   Defines two methods to recognize when a
                      window gains or loses input focus.


WindowListener        Defines seven methods to recognize when a
                      window is activated, closed, deactivated,
                      deiconified, iconified, opened, or quit.
Listener Interfaces and associated Event Classes

    ActionEvent             ActionListener

    MouseEvent              MouseListener
                            MouseMotionListener

    KeyEvent                KeyListener

    TextEvent               TextListener

    AdjustmentEvent         AdjustmentListener

    ContainerEvent          ContainerListener

    FocusEvent              FocusListener

    ItemEvent               ItemListener

    TextEvent               TextListener

    WindowEvent             WindowListener
The ActionListener Interface
  This interface defines the actionPerformed() method that is invoked when an
  action event occurs. Its general form is shown here:
        void actionPerformed(ActionEvent ae)

The AdjustmentListener Interface
       void adjustmentValueChanged(AdjustmentEvent ae)

The ComponentListener Interface
  This interface defines four methods that are invoked when a component is
  resized, moved, shown, or hidden.
        void componentResized(ComponentEvent ce)
        void componentMoved(ComponentEvent ce)
        void componentShown(ComponentEvent ce)
        void componentHidden(ComponentEvent ce)

The ItemListener Interface
        void itemStateChanged(ItemEvent ie)
The ContainerListener Interface
  When a component is added or removed to and from a container the following
  methods are invoked.
       void componentAdded(ContainerEvent ce)
       void componentRemoved(ContainerEvent ce)

The KeyListener Interface
       void keyPressed(KeyEvent ke)
       void keyReleased(KeyEvent ke)
       void keyTyped(KeyEvent ke)

The MouseListener Interface
      void mouseClicked(MouseEvent me)
      void mouseEntered(MouseEvent me)
      void mouseExited(MouseEvent me)
      void mousePressed(MouseEvent me)
      void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
      void mouseDragged(MouseEvent me)
      void mouseMoved(MouseEvent me)

The WindowListener Interface
       void windowActivated(WindowEvent we)
       void windowClosed(WindowEvent we)
       void windowClosing(WindowEvent we)
       void windowDeactivated(WindowEvent we)
       void windowDeiconified(WindowEvent we)
       void windowIconified(WindowEvent we)
       void windowOpened(WindowEvent we)

The MouseWheelListener Interface
      void mouseWheelMoved(MouseWheelEvent mwe)

The TextListener Interface
        void textChanged(TextEvent te)
Adapter Classes
 Java provides a special feature, called an adapter class, that can simplify the
  creation of event handlers in certain situations.

 An adapter class provides an empty implementation of all methods in an
  event listener interface.

 Adapter classes are useful when you want to receive and process only some of
  the events that are handled by a particular event listener interface.

 You can define a new class to act as an event listener by extending one of the
  adapter classes and implementing only those events in which you are interested.
Table 20-4 lists the commonly used adapter classes in java.awt.event and
corresponding interfaces.


 Adapter Class                           Listener Interface
  KeyAdapter                              KeyListener
  MouseAdapter                            MouseListener
  MouseMotionAdapter                      MouseMotionListener
  WindowAdapter                           WindowListener
  ComponentAdapter                        ComponentListener
  ContainerAdapter                        ContainerListener
  FocusAdapter                            FocusListener
Inner Class
 An inner class is a class defined within other class, or within an
  expression.

  //Inner class demo.
  import java.applet.*;
  import java.awt.event.*;
  /*<applet code="InnerClassDemo" width=200 height=100></applet>*/
  public class InnerClassDemo extends Applet{
       public void init() {
                addMouseListener(new MyMouseAdapter());
       }
       class MyMouseAdapter extends MouseAdapter {
                public void mousePressed(MouseEvent me) {
                        showStatus("Mouse Pressed");
                }
       }
  }
Anonymous Inner Class
 An anonymous inner class is one that is not assigned a name.


//Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*<applet code="AnonymousInnerClassDemo" width=200
   height=100></applet>*/

public class AnonymousInnerClassDemo extends Applet{
  public void init() {
        addMouseListener(new MouseAdapter() {
                       public void mousePressed(MouseEvent me) {
                       showStatus("Mouse Pressed");
                       }
        });
  }
}
Frame
 Frame is a window that is not contained inside another window.



 Frame is the basis to contain other user interface components in Java
  graphical applications.


 The Frame class can be used to create windows. Frame’s constructors:

                Frame( )
                Frame(String title)


 After a frame window has been created, it will not be visible until you
  call setVisible( true).
Frame Location
 By default, a frame is displayed in the upper- left corner of the screen.


 To display a frame at a specified location, use the setLocation(x,y) method in
  the Frame class.


          (0,0)

                  Screen

                           (x, y)



                                         Frame
                                                   frameHeight   screenHeight




                                      frameWidth




                                    screenWidth
//Method 1
import java.awt.*;
public class MyFrame{
  public static void main( String args[]){
        Frame f = new Frame("MyFrame");
        f.setSize(300,200);
        f.setVisible(true);
  }
}
//Method 2
import java.awt.*;
public class MyFrame extends Frame{
         MyFrame(){
                  super(“title of Frame”);
                  setSize(300,200);
                  setVisible(true);
         }
}
class ExFrame{
   public static void main( String args[]){
          new MyFrame();
    }
}
//Method 3
import java.awt.*;
public class MyFrame extends Frame{
        MyFrame(){
                 super(“title of Frame”);
                 setSize(300,200);
                 setVisible(true);
        }
        public static void main( String args[]){
                  new MyFrame();
        }
}
User interface components

     Label            Button          Scrollbar

     TextField        TextArea        List

     Checkbox         CheckboxGroup   Choice

     MenuBar          Menu            MenuItem

     …
Label
 Labels are passive controls that do not support any interaction with the
 user.

 Constructors
     Label()
     Label( String text )
     Label( String text , int alignment )

 Alignment Constants
        Label.LEFT , Label.RIGHT , Label.CENTER

 Methods
     void setText(String text)
     String getText()
     void setAlignment(int alignment)
     int getAlignment()
  //Label Example
import java.awt.*;
public class ExLabel extends Frame
{
        public ExLabel()
        {
                 super("Label test");
                 Label label1 = new Label(“Enter User Name");
                 add( label1 );
                 setSize(300,200);
                 setVisible(true);
        }
        public static void main( String args[] )
        {
                 new ExLabel();
        }
}
Button
Constructors
               Button()
               Button(String title )

Methods
               getLabel()
               setLabel()
import java.awt.*;     import java.awt.event.*;       import java.applet.*;
/* <applet code="ButtonDemo" width=250 height=150> </applet>*/
public class ButtonDemo extends Applet implements ActionListener {
           String msg = "“;     Button yes, no, maybe;
           public void init() {
                     yes = new Button("Yes");              no = new Button("No");
                     maybe = new Button("Undecided");
                     add(yes);            add(no);         add(maybe);
                     yes.addActionListener(this); no.addActionListener(this);
                     maybe.addActionListener(this);
           }
           public void actionPerformed(ActionEvent ae) {
                                 String str = ae.getActionCommand();
                                 if(str.equals("Yes")) {
                                              msg = "You pressed Yes.";
                                 }
                                 else if(str.equals("No")) {
                                              msg = "You pressed No.";
                                 }
                                 else {
                                              msg = "You pressed Undecided.";
                                 }
                                 repaint();
                      }
                      public void paint(Graphics g) {
                                  g.drawString(msg, 6, 100);
                      }           }          }
Checkbox

Constructors
    Checkbox()
    Checkbox(String text)
    Checkbox(String text , boolean state)
    Checkbox(String text , CheckboxGroup group , boolean state)

Methods
    String getLabel()
    void setLabel()
    boolean getState()
    void setState()
CheckboxGroup, Choice and List
Three types of interface components are used to allow the user to select
one item from a large number of possibilities.

   First is a group of connected check boxes with the property that
    only one can be selected at a time.( also called radio buttons ).

   Second is Choice.


   A third is a List. A List is similar to a choice, but several items
    will be displayed at a time.
CheckboxGroup / Radio buttons

Constructors
       CheckboxGroup()
       Checkbox(String text , CheckboxGroup group , boolean state)

Methods
          Checkbox getSelectedCheckbox( )
          void setSelectedCheckbox(Checkbox which)
Choice
Constructors
        Choice()

Methods
          void add(String) – To add items to the list
          String getItem(int)
          String getSelectedItem()
          void select(int index)
          void select(String name)
List
Constructors
        List()
        List(int rows)
        List(int rows, boolean multipleMode)

Methods
          void add(String)                 //To add item to the end of the list
          void add(String, int index) //To add item at an specified index
          int getItemCount()      //To get the count of items in the list
          String getItem(int)     //To get the specified item from the list
          void remove(int)        //To remove the item form the list
          String getSelectedItem() //To get selected item from the list
  TextField
Constructors
        TextField()
        void setText(String)
        TextField(int columns)
        TextField(String text)
        TextField(String text, int columns)
Methods
        void setText(String)
        String getText()
        void setEchoChar(char)          //To enter text that is not displayed
        void setEditable(bolean)        //if false, text cann’t be modified
//TextField Example
import java.awt.*;      import java.awt.event.*;             import java.applet.*;
/*<applet code="TextFieldDemo" width=380 height=150></applet>*/
public class TextFieldDemo extends Applet implements ActionListener {
            TextField name, pass;
            public void init() {
                        Label namep = new Label("Name: ", Label.RIGHT);
                        Label passp = new Label("Password: ", Label.RIGHT);
                        name = new TextField(1);
                        pass = new TextField(8);
                        pass.setEchoChar('?');
                        add(namep);              add(name);             add(passp);       add(pass);
                        // register to receive action events
                        name.addActionListener(this);
                        pass.addActionListener(this);
            }
            // User pressed Enter.
            public void actionPerformed(ActionEvent ae) {
                        repaint();
            }
            public void paint(Graphics g) {
                        g.drawString("Name: " + name.getText(), 6, 60);
                        g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80);
                        g.drawString("Password: " + pass.getText(), 6, 100);
            }
}
TextArea
Constructors
        TextArea()
        TextArea(String text)
        TextArea(int rows, int numChars)
        TextArea(String text , int rows, int numChars)
        TextArea(String str, int numLines, int numChars, int sBars)
        sBars must be one of these values:
        SCROLLBARS_BOTH                        SCROLLBARS_NONE
        SCROLLBARS_HORIZONTAL_ONLY
                SCROLLBARS_VERTICAL_ONLY

Methods
      void append(String)
      void setText(String)
      String getText()
      void setEditable(boolean)
      void insert(String str, int index)
// Demonstrate TextArea.
import java.awt.*;             import java.applet.*;
/*<applet code="TextAreaDemo" width=300 height=250></applet>*/
public class TextAreaDemo extends Applet {
          public void init() {
                   String val = "There are two ways of constructing " +
                   "a software design.\n" +
                   "One way is to make it so simple\n" +
                   "that there are obviously no deficiencies.\n" +
                   "And the other way is to make it so complicated\n" +
                   "that there are no obvious deficiencies.\n\n" +
                   " -C.A.R. Hoare\n\n" +
                   "There's an old story about the person who wished\n" +
                   "his computer were as easy to use as his telephone.\n" +
                   "That wish has come true,\n" +
                   "since I no longer know how to use my telephone.\n\n" +
                   " -Bjarne Stroustrup, AT&T, (inventor of C++)";

                  TextArea text = new TextArea(val, 10, 30);
                  add(text);
         }
}
Scrollbar
 Scroll bars are used to select continuous values between a specified
 minimum and maximum.

 The maximum and minimum values can be specified.

The line increment can be specified( the amount scroll bar will move
when it is touched in the line ends).

 The page increment can be specified ( the amount scroll bar will move
 when it is touched in the background area between the thumb and the
 end).
Constructors
           Scrollbar()
           Scrollbar(int style)
           Scrollbar(int style, int initialValue, int thumbSize, int min, int max)

Constants
               Scrollbar.VERTICAL
               Scrollbar.HORIZONTAL
Methods

                getValue()
                setValue(int newValue);
                void setUnitIncrement(int newIncr)
                void setBlockIncrement(int newIncr)
                int getMinimum( )
                int getMaximum( )

      Minimum : default 0.                 Maximum : default 100
      Default line increment is 1          Default page increment is 10.
import java.awt.*;     import java.awt.event.*;         import java.applet.*;
/*<applet code="SBDemo" width=300 height=200></applet>*/
public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener {
            String msg = "";      Scrollbar vertSB, horzSB;        int width = 300, height = 200;
            public void init() {
                       vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0,height);
                       horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
            add(vertSB);                      add(horzSB);
            vertSB.addAdjustmentListener(this);                    horzSB.addAdjustmentListener(this);
            addMouseMotionListener(this);
            }
            public void adjustmentValueChanged(AdjustmentEvent ae) {
                       repaint();
            }
            public void mouseDragged(MouseEvent me) {
                       int x = me.getX();               int y = me.getY();
                       vertSB.setValue(y);              horzSB.setValue(x);
                       repaint();
            }
            public void mouseMoved(MouseEvent me) {}
            public void paint(Graphics g) {
                       msg = "Vertical: " + vertSB.getValue();
                       msg += ", Horizontal: " + horzSB.getValue();
                       g.drawString(msg, 6, 160);
            }
}
MenuBar , Menu and MenuItem
1. To create a menu bar, first create an instance of MenuBar class.
   This class only defines the default constructor. A menu bar contains one or
   more Menu objects.
   Constructor:             MenuBar( )
   Methods:                 setMenuBar(menubarInstance)
                            menubarInstance.add(menuInstance)

2. Next, create instances of Menu class.
   Constructors:            Menu( )
                            Menu(String menuName)
   Methods:                 menuInstance.add(menuitemInstance)

3. Add menu items using MenuItem class.
   Constructors:
                MenuItem( )
                MenuItem(String itemName)
                MenuItem(String itemName, MenuShortcut keyAccel)
 You can disable or enable a menu item by using the setEnabled( ) method.


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


 You can change the name of a menu item by calling setLabel( ).


 You can retrieve the current name by using getLabel( ).
import java.awt.*;
public class ExMenubar extends Frame implements ActionListener{
         public ExMenubar(){
                  super("Menubar test");
                  MenuBar mbar = new MenuBar();
                  setMenuBar(mbar);
                  Menu file = new Menu("File");
                  MenuItem item1, item2, item3, item4, item5;
                  file.add(item1 = new MenuItem("New..."));
                  file.add(item2 = new MenuItem("Open..."));
                  file.add(item3 = new MenuItem("Close"));
                  file.add(item4 = new MenuItem("-"));
                  file.add(item5 = new MenuItem("Quit..."));
                  mbar.add(file);
                  setSize(300,400);
                  setVisible(true);
                  //item1.addItem
         }
         public static void main(String args[]){
                  new ExMenubar();                  }
}
Dialog Boxes
 A dialog box is a special window used to alert user or take input from user.


 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, for example, 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, you cannot access other parts of your
  program until the dialog box is closed.

 When a modeless dialog box is active, you can access other parts of your
  program.
Constructors
   Dialog(Frame parentWindow, boolean mode)
   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.
import java.awt.*;
public class ExDialog extends Frame{
        public ExDialog()       {

               Dialog d = new Dialog(this ,"Dialog", false);
               d.add("Center", new Label("Dialog Box"));
               d.add("South“, new Button("OK"));

               d.pack();
               d.setVisible(true);
       }
       public static void main(String args[]){
                new ExDialog();
       }
}
Canvas
A Canvas is a two-dimensional area used to draw some shapes on it using the
Graphics.

Constructors
         Canvas()

Methods
          setSize(int width, int height)
          setBackground(Color )
import java.awt.*;

public class ExCanvas extends Frame{
        public ExCanvas(){
                 setLayout(new FlowLayout());
                 Canvas can1 = new Canvas();
                 can1.setSize(200,100);
                 can1.setBackground(Color.red);
                 add( can1 );
                 setSize(200,300);
                 setVisible(true);
        }
        public static void main(String args[]){
                 new ExCanvas();
        }
}
 Panel
This is simplest invisible container that holds GUI components.

It is recommended that you place the user interface components in panels and
 place the panels in a frame.

You can also place panels in a panel.

FlowLayout is the default layout for panel.

      Panel()
      Panel(LayoutManager layout)
import java.awt.*;
public class ExPanel extends Frame{
        public ExPanel(){
                setLayout(new FlowLayout());
                Panel pan1 = new Panel();
                pan1.setSize(200,100);
                pan1.setBackground(Color.red);
                pan1.setLocation(50,50);
                add( pan1 );

               Button button1 = new Button(“ok");
               Button button2 = new Button(“cancel");
               pan1.add( button1 );
               pan1.add( button2 );
       }
       public static void main(String args[]){
                new ExPanel();
       }
}
ScrollPane
 It is similar to a panel.

 It can hold only one Component.

  If size of the component held is larger than the size of the ScrollPane,
   Scroll bars will be automatically generated.

  It does not have a LayoutManager

 Constructors
                 ScrollPane()
import java.awt.*;
public class ExScrollPane extends Frame{
        public ExScrollPane(){
                 ScrollPane sPane1 = new ScrollPane();
                 sPane1.setSize(200,100);
                 sPane1.setBackground(Color.red);
                 sPane1.setLocation(50,50);
                 Panel pan1 = new Panel();
                 TextArea text1 = new TextArea(300,500);
                 pan1.add( text1 );
                 sPane1.add( pan1 );
                 add( sPane1 );
                 setSize(200,300);
                 setVisible(true);
        }
        public static void main(String args[]){
                 new ExScrollPane();
        }
}
Graphics
 Graphics object draws pixels on the screen that represent text and other
  graphical shapes such as lines, ovals, rectangles, polygons etc.

 The graphics class is an abstract class(i.e. Graphics objects can not be
  instantiated.)

 A graphics context is encapsulated by the Graphics class and is obtained
  in two ways:

      It is passed to an applet when one of its various methods, such as
       paint( ) or update( ), is called.

      It is returned by the getGraphics() method of Component.
public void paint(Graphics g)
   The paint(Graphics g) method is common to all components and containers.

   It is needed if you do any drawing or painting other than just using standard
    GUI components.

   Never call paint(Graphics g), call repaint( )

How does the paint(Graphics g) method get called?
    It is called automatically by Java whenever the component or
     container is loaded, resized, minimized, maximized.

    You can cause the paint method to be called at any time by calling the
     component’s repaint() method.
class myFrame extends Frame{
          ……..
          ……..
    public void paint(Graphics g){
          g.drawOval(x1,y1,width,height);
          ……
   }
}
The repaint() method will do two things:

1. It calls update(Graphics g), which writes over the old drawing in background
   color (thus erasing it).

2. It then calls paint(Graphics g) to do the drawing.



                                                                x
  Java coordinate system            ( 0,0)


                                                        (x,y)
                                         y
Graphics methods for drawing shapes
 g.drawString (str, x, y);                   //Puts string at x,y

 g.drawLine( x1, y1, x2, y2 )        //Line from x1, y1 to x2, y2

 g.drawRect( x1, y1, width, height)
                      //Draws rectangle with upper left corner x1, y1

 g.fillRect(x1, y1, width, height)           //Draws a solid rectangle.

 g.drawRoundRect( x, y, width, height,arcWidth, arcHeight )
                   //Draws rectangle with rounded corners.

 g.fillRoundRect( x, y, width, height,arcWidth, arcHeight )
                       //Draws a solid rectangle with rounded corners.
(x, y)

            arc height                  drawRoundRect
                                        parameters

               arc width   height




                width
                               (x, y)



    drawOval parameters
                                                        height




                                         width
g.drawOval(x1, y1, width, height)
    //Draws an oval with specified width and height. The bounding
    rectangle’s top left corner is at the coordinate (x,y).The oval
    touches all four sides all four sides of the bounding rectangle.

g.fillOval(x1, y1, width, height)                //Draws a filled oval.

g.setColor(Color.RED)
             //Sets color, it is remain active until new color is set.
g.drawArc(x1, y1, width, height, startAngle,arcAngle)
    //Draws an arc relative to the bounding rectangle’s top-left
    coordinates with the specified width and height. The arc
    segment is drawn starting at startAngle and sweeps arcAngle
    degrees.



             90                           90




  180                     0    180                    0




           270                           270

         Positive angle              Negative angle
 Drawing Polygons and Polylines
 Polygon - multisided shape
 Polyline - series of connected points
 Methods of class Polygon


  drawPolygon( xPoints[], yPoints[], points )
    //Draws a polygon, with x and y points specified in arrays. Last
      argument specifies number of points
    //Closed polygon, even if last point different from first.

  drawPolyline ( xPoints[], yPoints[],points )
    //Draws a polyline
Font
 Fonts are encapsulated by the Font class.


 To select a new font, you must first construct a Font object that
  describes that font.
                Font(String fontName, int fontStyle, int pointSize)
                //Here, fontName specifies the name of the desired font.

 All Java environments will support the following fonts:
  Dialog, DialogInput, Sans Serif, Serif, Monospaced and Symbol.

 The style of the font is specified by fontStyle. It may consist of one or
  more of these three constants:
       Font.PLAIN                Font.BOLD                 Font.ITALIC
  void setFont(Font fontObj)
                //To set the specified Font .
               //It is defined in Component class.
               //Here, fontObj is the object that contains the desired font.

  Font getFont()      //To obtain information about the currently
                      selected font which is defined in Graphics class
Methods in Font Class:
 String getName()             //To get the name of the Font
 String getFamily();          //To get family name of the Font
 int getSize();               //To get the size of the Font
 int getStyle();              //To get the style of the Font
Layout Managers

 Arranges and lays out the GUI components on a container.


 Every container has a default Layout Manager:
   Panel                      FlowLayout
   Window (Frame)             BorderLayout

 Types:
       Flow Layout             Border Layout          Grid Layout
       Card Layout             Gridbag Layout

 To set layout manager:
       myContainer.setLayout( new LayoutManger() );
Flow Layout
 The Flow Layout manager arranges the components left-to-right, top-
  to-bottom in the order they were inserted into the container.

 When the container is not wide enough to display all the components,
  the remaining components are placed in the next row, etc.

 By default each row is centered.


 The line alignment can be:
        FlowLayout.LEFT
        FlowLayout.CENTER
        FlowLayout.RIGHT
Flow Layout Example




         English     French     Greek


          Japanese     German


           Spanish       Portuguese


          Arabic     Chinese    Russian
Flow Layout Constructors
 FlowLayout()
  //A centered alignment and a default 5-unit horizontal and vertical gap.

 FlowLayout(align)
  align – alignment used by the manager. A default 5-unit horizontal and
  vertical gap.

 FlowLayout(align, hgap, vgap)
  //align – alignment used by the manager
  //hgap – horizontal gaps between components
  //vgap – vertical gaps between components
Border Layout
 The Border Layout manager arranges components into five regions: North,
  South, East, West, and Center.

 Components in the North and South are set to their natural heights and
  horizontally stretched to fill the entire width of the container.

 Components in the East and West are set to their natural widths and
  stretched vertically to fill the entire width of the container.

 The Center component fills the space left in the center of the container.

 If one or more of the components, except the Center component, are
  missing then the rest of the existing components are stretched to fill the
  remaining space in the container.

 The positional constraints are:
     BorderLayout.NORTH               BorderLayout.SOUTH
     BorderLayout.EAST                BorderLayout.WEST
     BorderLayout.CENTER
BorderLayout Manager

                            North



             West          Center          East



                            South




  To set BorderLayout:
                add( new Button(“ok”), BorderLayout.NORTH);
Border Layout Constructors

 BorderLayout()
      //No vertical or horizontal gaps.

 BorderLayout(hgap, vgap)
      //hgap – horizontal gaps between components
      //vgap – vertical gaps between components
Grid Layout

  Container is divided into a grid where components are placed in
   rows and columns.

  Every component has the same width and height.


  Example
Grid Layout Constructors
  GridLayout()
        //A single row and no vertical or horizontal gaps.

  GridLayout(r, c)
        //r – number of rows in the layout
        //c – number of columns in the layout
        //No vertical or horizontal gaps.

  GridLayout(r, c, hgap, vgap)
        //r – number of rows in the layout
        //c – number of columns in the layout
        //hgap – horizontal gaps between components
        //vgap – vertical gaps between components
CardLayout
 CardLayout places components (usually panels) on top of each other
  in a stack like a deck of cards.

 You can see only one card at a time.

 By default, the first card is visible.

 We can put a cards on top using another control by using the methods
  next(), previous(), first(), last(), and show().
Constructor:                  CardLayout()

Methods:
               public void first(Container parent);
               public void next(Container parent);
               public void previous(Container parent);
               public void last(Container parent);
               public void show(Container parent, String name);



                                           New Card




                                    First Card

 add(component, name)
import java.awt.*;                   import java.awt.event.*;
public class CardLayoutDemo extends Frame implements ActionListener, MouseListener {
   Checkbox winXP, winVista, solaris, mac;
   Button Win, Other;
   Panel osCards;
   CardLayout cardLO;
   public CardLayoutDemo(){
             setLayout(new BorderLayout());
             cardLO = new CardLayout();
             Panel tabs=new Panel();
             Win = new Button("Windows");
             Other = new Button("Other");
             tabs.add(Win);
             tabs.add(Other);
             add(tabs,BorderLayout.NORTH);
             osCards = new Panel();
             osCards.setLayout(cardLO); // set panel layout to card layout
             Panel winPan = new Panel();
             winXP = new Checkbox("Windows XP", null, true);
             winVista = new Checkbox("Windows Vista");
             // add Windows check boxes to a panel
             winPan.setBackground(Color.CYAN);
             winPan.add(winXP);
             winPan.add(winVista);
// Add other OS check boxes to a panel
           Panel otherPan = new Panel();
           solaris = new Checkbox("Solaris");
           mac = new Checkbox("Mac OS");
           otherPan.setBackground(Color.RED);
           otherPan.add(solaris);
           otherPan.add(mac);

          // add panels to card deck panel
          osCards.add(winPan, "Windows");
          osCards.add(otherPan, "Other");
          // add cards to main applet panel
          add(osCards,BorderLayout.CENTER);
          // register to receive action events

          Win.addActionListener(this);
          Other.addActionListener(this);

          // register mouse events
          addMouseListener(this);
          setSize(250,250);
          setVisible(true);
          }
public Insets getInsets(){
                       return new Insets(30,30,30,30);
           }
           public void mousePressed(MouseEvent me) {
                                  cardLO.next(osCards);
           }
           public void mouseClicked(MouseEvent me) {                   }
           public void mouseEntered(MouseEvent me) {                   }
           public void mouseExited(MouseEvent me) {                    }
           public void mouseReleased(MouseEvent me) {                  }
           public void actionPerformed(ActionEvent ae) {
                       if(ae.getSource() == Win) {
                                  cardLO.first(osCards);   //cardLO.show(osCards, "Windows");
                       }
                       else {
                                  cardLO.last(osCards);      //cardLO.show(osCards, "Other");
                       }
           }
           public static void main(String arg[]){
                       new CardLayoutDemo();
           }
}
GridBagLayout Layout Manager

 Flexible GridBagLayout
   Components can vary in size
   Components can occupy multiple rows and columns
   Components can be added in any order


 There are two classes that are used:
    GridBagLayout: Provides the overall layout manager.
    GridBagConstraints: Defines the properties of each component in
    the grid such as placement, dimension and alignment
Specifying a GridBagLayout

 To use a gridbag layout, you must declare the GridBagLayout and
GridBagConstaraints object and attach the layout to your applet.

Example:

    GridBagLayout gridbag = new GridBagLayout();

    GridBagConstraints constraints = new GridBagConstraints();

    setLayout(gridbag);
Setting Constraints for Components
   For each component that you add to the gridbag layout, you must first
    set an instance of the GridBagContraints class.

   Let us look at an example:

    constraints.gridx = 0 // put component in first cell.
    constraints.gridy = 0
    gridbag.setConstraints(button1, constraints);
                                       //set the constraints to button1.
    add(button1);                      //add to the Frame
Precisely Placing Components
                        Column
                  0        1     2




            0

            1

     Row    2

            3
GridBagConstraints Data Members
The following are the constraints to control the component:
  gridx, gridy, gridwidth, gridheight, weightx, weighty, ipadx, ipady , fill

constraints.gridx=0;               //To set the column (Default is RELATIVE).
constraints.gridy=0;               //To set the row (Default is RELATIVE).



constraints.gridwidth = 2;         //Joins two cells horizontally
constraints.gridheight = 2;        //Joins two cells vertically
                                   //Default value is 1.
constraints.weightx=2;        //Determines horizontal spacing between cells.
constraints.weighty=3;        // Determines vertical spacing between cells.
                              //Default value is 0.
constraints.ipadx=2;
       //Specifies extra horizontal space that surrounds a component within a cell.
constraints.ipady=0;
      //Specifies extra vertical space that surrounds a component within a cell.
         //Default is 0.
fill     //Resizing rules for a component smaller than its display area;
         //HORIZONTAL makes component as wide as the display area;
         //VERTICAL as tall; BOTH expands it vertically and horizontally.
         //NONE (default) is default.
Examples:
constraints.fill = GridBagConstraints.BOTH;             //Fill cell height & width
constraints.fill = GridBagConstraints.HORIZONTAL;                  //Fill cell width

				
DOCUMENT INFO
Categories:
Tags:
Stats:
views:8
posted:10/4/2012
language:English
pages:99