The Applet Class

 

An Applet does not have a main method.  An Applet is a program that is loaded and executed by another program – usually a browser or appletviewer.

 

An applet reference line can be contained within HTML code.

(put the following line in any html file and to run the SampleApplet.class)

 

<applet code = SampleApplet.class width = 500 height = 500>

</applet>

 

When an Applet is embedded in an HTML page, it is downloaded remotely across the Net and run on your PC. 

 

Applet Source Code

 

            The source is used to compile an applet class.

 

import java.awt.*;

import java.applet.Applet;

public class SampleApplet extends Applet {

    private static int initCount= 0;

    private static int paintCount = 0;

 

    public void init(){  

      // Called when the applet is loaded

     

        initCount++;  // increase every time the init() is called

        setBackground(Color.yellow);

        setForeground(Color.blue);

    }

 

    public void paint(Graphics g) { // another override

      // Called by the browser when the applet is to be drawn.

      // or when suggested by repaint().

 

        paintCount++;  // increased every time paint() is called

        g.setFont(new Font("SansSerif", Font.ITALIC, 12));

        g.drawString("init() method activated " + initCount

                  + " time" + ((initCount!= 1)?"s":" "), 20, 20);

        g.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 14));

        g.drawString("paintCount() method activated " + paintCount

                    + " time" + ((paintCount != 1)?"s":" "), 20, 40);

  }

}

 

      To run the applet, activate the HTML code which contains the reference to the applet. 

 

Applet limitation:  Applets embedded within web pages are not allowed to do local disk I/O.

 

 

 

 

           

Applet Methods

 

 

Applet Methods

Action

  resize(int width, int height)

Request applet be resized*

  init()

Initialize variables

  start()

Start execution

  stop()

Stops execution

  destroy()

Release resources

  paint(Graphics g)

Paint  --  Inherited from parent

  repaint(Graphics g)

Suggestion to Paint --  Inherited from parent*

 

* Methods the programmer can call

   All other methods are called by the system

 

 

 

Screen Coordinates are used for Positioning Graphics --

 

A point on the screen is a picture element (pixel).  The pixel is positioned at the intersection of its horizontal and vertical coordinates. 

·        The horizontal coordinate (horiz) starts as zero at the left.  Increasing the value of horiz moves the pixel further to the right.

·        The vertical coordinate (vert) starts as zero at the top.  Each increase in the value of vert moves the pixel further to the bottom.

 

 

The width and height of a graphic object is measured in pixels.

·        Width (w). As w increases, the object is wider.

·        Height (h).  As h increases, the object is taller.

 

 

In order to accomplish a task, the Applet needs overrides to parent methods

and work done by other classes such as Graphics, Color and Font.

 

 

 

Color

 

The Color class represents colors as having levels of Red, Green and Blue saturation.

Every color has an implicit value of 255 for full saturation.

Explicit values to the constructor can range from 0 to 255.

 

 

Color Constructors

Action

Color(int red, int green, int blue)

Creates a color with the specified values

(0 – 255)

Color(float red, float green, float blue)

Creates a color with the specified values

Color(redGreenBlue)

Creates a color with the specified values

blue in bits 0-7, green in bits 8-15, red in 16-23

Color Methods

Action

Color brighter()

Creates a brighter version of current Color

Color darker()

Creates a darker version of current Color

int getBlue()

Returns the blue component (0-255)

int getGreen()

Returns the green component (0-255)

int getRed()

Returns the red component (0-255)

Color Constants

 

black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow

 

 

 

 

/* Draw each of 100 cells with randomly

 * chosen colors.

 */

 

import java.awt.*;

import java.applet.Applet;

 

public class ColorChips extends Applet {

  public void paint(Graphics g) {

    int h = getSize().height;

    int w = getSize().width;

    for (int i = 0; i < 10; i++)

      for (int j = 0; j < 10; j++) {

        float red = (float)Math.random();

        float green = (float)Math.random();

        float blue = (float)Math.random();

        Color color = new Color(red,green,blue);

        g.setColor(color);

        g.fillRect(i*w/10,j*h/10,w/10,h/10);

      }

  }

}

 

 

 

Font

 

The Font class represents fonts for textual display. Five font names are recognized by any Java environment: SansSerif, Serif, Mono-space     d, Dialog and DialogInput.

 

 

Font Constructor

Action

Font(String name, int style, int size)

Creates a Font with the specified values

Font Methods

Action

String getName()

returns the name of the font

int getSize()

returns the size

int getStyle()

returns the style

Font Constants

 

BOLDfg, ITALIC, PLAIN

 

 

 

 

//Copyright (c) 1998-2001, Art Gittleman

 

/* Draws the different fonts, trying all the

 * styles, and using various point sizes.  Draws

 * all text relative to the applet's size.  Uses

 * the init method to compute quantities that

 * don't change.

 */

 

import java.awt.*;

import java.applet.Applet;

 

public class Text extends Applet {

  private Font arialBold24;

  private Font timesItalic14;

  private Font courierPlain18;

  private Font lucindaBI20;

  private Font serifPlain18;

  private String arial;       //  The string we want to center

  private int arialStart;     //  x position for the centered string

  private int arialWide;      //  The width of the centered string.

 

  public void init() {

    arialBold24 = new Font("Arial",Font.BOLD,24);

    timesItalic14 = new Font("Times New Roman",Font.ITALIC,14);

    courierPlain18 = new Font("Courier",Font.PLAIN,18);

    lucindaBI20 = new Font

              ("Lucinda Sans Regular",Font.BOLD+Font.ITALIC,20);

    serifPlain18 = new Font("Serif",Font.PLAIN,18);

    setFont(arialBold24);

    FontMetrics metrics = getFontMetrics(arialBold24);

    arial = arialBold24.getName();

    arialWide = metrics.stringWidth(arial);

  }

  public void paint(Graphics g) {

    Dimension d = getSize();

    int w = d.width;                 //  The width of the applet  

    int h = d.height;                //  The height of the applet 

    int arialStart = (w-arialWide)/2;

    int otherStart = w/4;            

    g.drawString(arial,arialStart,h/6);

    g.setFont(timesItalic14);

    g.drawString(timesItalic14.getName(),otherStart,2*h/6);

    g.setFont(courierPlain18);

    g.drawString(courierPlain18.getName(),otherStart,3*h/6);

    g.setFont(lucindaBI20);

    g.drawString(lucindaBI20.getName(),otherStart,4*h/6);

    g.setFont(serifPlain18);

    g.drawString(serifPlain18.getName(),otherStart,5*h/6);

  }

}

 

 

Graphics 

 

 

Each Applet has a Graphics object associated with it. 

Access to the graphics object is provided as a parameter to paint(Graphics g). 

 

 

Graphic Methods

Action

clearRect(int horiz, int vert, int w, int h)

Clears the specified rectangle by filling it with the background color of the current drawing surface.

Draw3DRect (int horiz, int vert, int w, int h,

    boolean raised)

Draws a 3-D highlighted outline of the specified rectangle.

drawArc (int horiz, int vert, int w, int h,

    int startAngle, int arcAngle)

Draws the outline of a circular or elliptical arc covering the specified rectangle.

drawLine(int horiz1, int vert1, int horiz2,

    int vert2)

Draws a line between horiz1,vert1 and horiz2, vert2

drawOval(int horiz, int vert, int w, int h)

Draws an oval outline

drawPolygon(int[] horiz, int[] vert,

    int nbrOfpoints

Draws a sequence of connected lines

drawRect(int horiz, int vert, int w, int h)

Draws outline of a rectangle

drawString(String str, int horiz, int vert)

Draws the text

Fill3DRect(int horiz, int vert, int w, int h,

    boolean raised)

Highlighted rectangle, filled with current color

fillArc(int horiz, int vert, int w, int h,

    int startAngle, int arcAngle)

Fills a circular arc

fillOval(int horiz, int vert, int w, int h)

Fills an oval

fillPolygon(int[] horiz, int[] vert,

    int nbrOfpoints

Fills a closed polygon

fillRect(int horiz, int vert, int w, int h)

Fills the rectangle

setColor(Color c)

Sets the color

setFont(Font f)

Sets the font

 

 

//Copyright (c) 1998, Arthur Gittleman

 

/*  Demonstrates drawing and filling 3D

 *  rectangles, and brightening and darkening

 *  colors.

 */

 

import java.awt.*;

import java.applet.Applet;

 

public class MoreColor extends Applet {

  public void paint(Graphics g) {

    g.setColor(Color.orange);

    g.fillRect(10,20,100,50);

    g.fill3DRect(150,20,100,50,true);

    g.fill3DRect(270,20,100,50,false);

    g.setColor(Color.orange.darker());

    g.fillOval(10,100,100,50);

    g.setColor(Color.orange.brighter());

    g.fillOval(150,100,100,50);

    g.setColor(Color.orange);

    g.draw3DRect(10,180,100,50,true);

    g.draw3DRect(150,180,100,50,false);

    g.setColor(Color.black);

    g.drawString("Orange",15,90);

    g.drawString("3-d Raised",150,90);

    g.drawString("3-d Recessed",270,90);

    g.drawString("Darker",25,170);

    g.drawString("Brighter",170,170);

    g.drawString("3-d Raised",20,250);

    g.drawString("3-d Recessed",160,250);    

  }

}

          

 

Abstract Windows Toolkit Class Hierarchy

 

 

The paint()method called in the sample Applet is not a method defined at the Applet level. 

The Applet inherits methods from its parent classes

 

 

 

           

 

 

 

The Abstract Windowing Toolkit (AWT)

 

 

is a single programmer interface (API) for dealing with common GUI components across different platforms.

 

The AWT library delegates the creation and behavior of the interface elements to the native GUI toolkit on each target platform.

 

 

 

 

Appearance of the GUI

 

 

            is dependent on the platforms executing the GUI.

 

Windows API

            OS/2 Presentation Manager API

            X-Windows API

            Mac API

 

 

 

 

Component

 

A component is an object with a graphical representation that can interact with the user.

Examples of components are the buttons, checkboxes, and scrollbars.

 

 

Component Methods

Action

add(Component comp)

Adds the Component to the end of this container

add(Component comp, int index)

Adds the Component to the index position

paint(graphics g)

Causes this component to be painted using the graphics object g.  *

remove(Component comp)

Removes the specified Component

remove(int index)

Removes the Component at index

removeAll()

Removes all the Components from the container

repaint()

Tell the system that this component needs to be redrawn

repaint(int horiz, int vert, int w, int h)

Redraw the component at a given location and size

setBackground(Color c)

Sets background color

setBounds(int horiz, int vert, int w, int h)

Changes the size and location of the Component

setFont(Font f)

Sets the Font of the Component

setForeground(Color c)

Sets the foreground color

setLayout(LayoutManager mgr)

Sets the layout manager for this container

setLocation(int horiz, int vert)

Changes the location of the Component

setSize(int w, int h)

Changes the size of the Component

update()

Default behavior is to erase Component by drawing over it with background color then call the paint() method.  *. 

 

*Called by the System

 

 

 

Subclasses of Component

 

Component is an abstract class.  The subclasses of Component define the Component methods above and add methods specialized to their purpose.

 

    Button

 

A Button is a graphic component that can be clicked. 

 

Button Constructors

Action

Button()

Creates a Button with no title

Button(String s)

Creates a Button labeled with the String given

Button Methods

 

String getLabel()

Returns the Button’s text label

setLabel(String s)

Replaces the label of the Button with the String s

 

 

    Canvas

 

A Canvas component is a blank rectangular area onto which the program can draw and/or trap input events from the user

The Canvas class should be extended in order to customize its appearance.  Override paint() to perform custom graphics.

 

Canvas Constructor

Action

Canvas()

Creates a Canvas

Canvas Methods

 

paint(Graphics g)

Called when the canvas will be painted

 

 

Checkbox

 

A Checkbox displays a toggle button. It has a boolean member indicating its state. 

A check box can be in either an "on" (true) or "off" (false) state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on."

 

Checkbox Constructors

Action

Checkbox(String s)

Creates a Checkbox with the label of the String given and sets the state to false

Checkbox(String s, boolean b)

In addition to above, sets the state to b.

Checkbox(String s, boolean b,

    CheckboxGroup g)

In addition to above, assigns Checkbox to a CheckboxGroup.

Checkbox Methods

 

String getLabel()

Returns the Checkbox’s text

boolean getState()

returns the current state (true or false)

setLabel(String s)

Replaces the label of the Checkbox with the String s

setState(boolean b)

Replaces the state with b

setCheckboxGroup(CheckboxGroup g)

Assigns Checkbox to a CheckboxGroup

 

   

CheckboxGroup (aka radio buttons)

 

CheckboxGroup has no visual appearance and is not a subclass of Component.  

CheckboxGroup provides a way to collect related Checkboxes – only one of which can be true at any one time.

Pushing any button sets its state to "on" and forces any other button that is in the "on" state into the "off" state.

 

CheckboxGroup Constructor

Action

CheckboxGroup()

Creates a CheckboxGroup

CheckboxGroup Methods

 

Checkbox getSelectedCheckbox()

Returns the Checkbox’s which has the true state

setSelectedCheckbox(Checkbox c)

Sets the state of Checkbox to true and turns other Checkboxes off

 

 

 

    Choice

 

Choice presents a pop-up menu of choices. The current choice is displayed as the title of the menu.

 

 

Choice Constructor

Action

Choice()

Creates a Choice

Choice Methods

 

add (String item)

Adds an item to the choice list

String getItem(int index)

Gets the String at index

int getSelectedIndex()

Gets index of currently selected item

String getSelectedItem()

Gets String of item selected

insert(String item, int index)

Inserts item at index

remove(int position)

Removes item at given position

remove(String item)

Removes first occurrence of item

removeAll()

Removes all items

select(int index)

Sets the selection to index

select(String item)

Selects matching string

 

 

 

    Label

 

A Label displays a single line of text.

A user cannot edit the text but it is changeable by the program.

 

Label Constructors

Action

Label(String s)

Creates a center-aligned Label displaying the String given

Label(String s, int alignment)

Creates a Label according to the alignment given and String

Label.LEFT, Label.RIGHT, Label.CENTER

Label Methods

 

String getText()

Returns the Label’s text

setText(String s)

Replaces the text in the Label with the String s

 

 

 

    List

 

List looks like a text area with a scrolling list of items.

The List can be set up so that the user can choose either one item or multiple items.

 

 

List Constructor

Action

List()

Creates a List in single selection mode

List(int rows)

In addition to above, sets the number of rows

List(int rows, boolean m)

In addition to above, sets multiple selection if m is true

List Methods

 

add(String item)

Adds an item to the list

add(String item, int index)

Adds item at index

addItem(String item)

Adds an item

deselect(int index)

Turns off selection

String getItem(int index)

Gets the String at index

int getSelectedIndex()

Gets index of currently selected item

int[] getSelectedIndexes()

Get selected indexes

String getSelectedItem()

Gets current selection as a String

String [] getSelectedItems()

Gets all selected items as a String array

remove(int position)

Removes item at given position

remove(String item)

Removes first occurrence of item

removeAll()

Removes all items

select(int index)

Sets the selection to index

 

 

 

    TextField

 

A TextField looks like a box with one line of text.

A user can edit the text and it is changeable by the program.

 

TextField Constructors

Action

TextField(int columns)

Creates a empty TextField wide enough to hold columns

TextField(String s)

Creates a TextField displaying the String given

TextField (String s, int columns)

Shows text within columns

TextField Methods

 

String getText()

Returns the text.* 

setEchoChar(char c)

Echo character prints instead of what is keyed

setText(String s)

Replaces the text with the String s

setColumns(int l)

Changes the number of columns to l

 

 

    TextArea

 

A TextArea looks like a box with multiple lines of text.

A user can edit the text and it is changeable by the program.

 

TextArea Constructors

Action

TextArea(int r, int c)

Creates empty TextArea with r rows and c columns

TextArea(String s)

Creates a TextArea displaying the String given

TextArea(String s, int r, int c)

Shows text within columns with r rows and c columns

TextArea(String s, int r, int c, int scrollbars)

Specify whether the area will have scrollbars

TextArea.SCROLLBARS_BOTH,

TextArea.SCROLLBARS_NONE,

TextArea.SCROLLBARS_HORIZONTAL_ONLY,

TextArea.SCROLLBARS_VERTICAL_ONLY

TextArea Methods

 

append(String s)

Concatenates s to currently existing TextArea

String getText()

Returns the text.* 

setText(String s)

Replaces the text with the String s

setColumns(int l)

Changes the number of columns to l

setRows(int r)

Changes the number of rows to r

 

 

 

import java.awt.*;

import java.applet.Applet;

public class ComponentsAndContainers extends Applet {

  Panel panel;

 

 

  public void init() {

    Button b = new Button("Button");

    b.setSize(100,50);

    add(b);

    add(new Checkbox("Checkbox"));

    List list = new List(3);

    list.add("ice");

    list.add("nice");

    list.add("mice");

    add(list);

    panel = new MyPanel();

    panel.setBackground(Color.blue);

    panel.add(new Button("Inside Panel"));

    add(panel);

    CheckboxGroup group = new CheckboxGroup();

    add(new Checkbox("This", true, group));

    add(new Checkbox("That", false, group));

    add(new Checkbox("Other", false, group));

    DrawOn canvas = new DrawOn();

    canvas.setBackground(Color.yellow);

    canvas.setSize(150,150);

    add(canvas);

  }

}

class MyPanel extends Panel {

    public Dimension getPreferredSize() {

      return new Dimension(100,100);

    }

  }

 

class DrawOn extends Canvas {

  public void paint(Graphics g) {

    g.drawString("Inside Canvas",20,20);

  }

}

 

Containers

 

A Container is a Component used to hold other components together for display purposes.

Since Container is a subclass of Component, it has access to all the component methods listed above.

 

Components added to a Container are added to the end of the list unless an index position is specified.

There is no limit to the number of components a Container may hold.

 

 

 

Container Methods

Action

add(Component c)

Adds the Component to the end of this container

add(Component c, Object constraints)

Adds the Component with specified constraint

Component[] getComponenets()

Gets all the components in this container

boolean isAncestorOf(Component c)

Checks if the component is contained in the hierarchy of this container

remove(Component comp)

Removes the specified Component

remove(int index)

Removes the Component at index

removeAll()

Removes all the Components from the container

setFont(Font f)

Sets the font

setLayout(LayoutManager mgr)

Sets the layout manager for the container

 

 

Container Hierarchy

 

There is no limit to how deeply they may be nested – Containers within Containers, etc.

            If a container is removed, all the components in that container are also removed.

 

 

Subclasses of Container

 

Container is an abstract class.  The subclasses of Container add methods specialized to their purpose.

 

 

Container

Use

Default Layout Manager

Panel

The simplest Container class

FlowLayout

Applet

Extends Panel

Displays components in a Web browser. 

Applets do not have a menu bar.

FlowLayout

Frame

Full functioning window with its own title and border.

BorderLayout

Window

Top-level window with no borders nor menubar

BorderLayout

Dialog

Top-Level window with title and border.  Used as “auxiliary” windows for input to stand-alone applications.

BorderLayout

 

 

 

 

 

LayoutManager

 

A LayoutManager determines the size, position and arrangement of components within a container. 

LayoutManagers differ in how the components are arranged. 

Some arrange the components in rows while others divide the display into regions.

 

 

           

FlowLayout 

 

 

A FlowLayout arranges Components from left to right until no more components will fit in a row – then another row is started. 

 

 

FlowLayout Methods

Action

setAlignment(int align)

Sets the alignment for this layout

FlowLayout.CENTER,

FlowLayout.LEFT,

FlowLayout.RIGHT

setHgap(int hgapPixels)

Sets the horizontal gap between components

setVgap(int vgapPixels)

Sets the vertical gap between components

 

 

FlowLayout Example:

 

import java.awt.*;

import java.applet.Applet;

public class Flow extends Applet {

  public Flow () {

    setLayout(new FlowLayout()); // Applet uses FlowLayout by default

    add(new Button("1"));

    add(new Button("2"));

    add(new Button("3"));

    add(new Button("4"));

    add(new Button("5"));

    add(new Button("6")); 

  }

}            

 

 

BorderLayout                                                                                                     

 

 

A BorderLayout divides a Container into 5 regions: North, South, East, West, and Center. 

Each region can hold one Component. 

Components may be resized to completely fill each region.

 

 

BorderLayout Methods

Action

setHgap(int hgapPixels)

Sets the horizontal gap between components

setVgap(int vgapPixels)

Sets the vertical gap between components

BorderLayout Constants

 

CENTER, EAST, NORTH, SOUTH, WEST

 

 

 

BorderLayout Example:

 

                  

import java.awt.*;

import java.applet.Applet;

public class Border extends Applet {

  public Border () {

    setLayout(new BorderLayout());

    add(new Button("North 1"),  BorderLayout.NORTH);

    add(new Button("South 2"),  BorderLayout.SOUTH);

    add(new Button("East 3"),   BorderLayout.EAST);

    add(new Button("West 4"),   BorderLayout.WEST);

    add(new Button("Center 5"), BorderLayout.CENTER);

    add(new Button(“Center 6”), BorderLayout.CENTER);  // last one in wins!

  }

}

 

            Modify the program above so that the CENTER regions contains buttons Center 5 and Center 6.

 

 

GridLayout 

 

 

A GridLayout divides a Container into rows and columns to form a rectangular grid. 

Each rectangle can hold one Component. 

When adding Components, they will fill the cells from left to right, top to bottom order.

Components may be resized to completely fill each region.

Each Component will be the same size.

 

 

GridLayout Constructor

Acton

GridLayout(int r, int c)

Creates a grid layout with r rows and c columns

GridLayout Methods

 

setHgap(int hgapPixels)

Sets the horizontal gap between components

setVgap(int vgapPixels)

Sets the vertical gap between components

 

 

GridLayout Example:

 

         

import java.awt.*;

import java.applet.Applet;

public class Grid extends Applet {

  public void init () {

    int row = 3, col = 2;

    setLayout(new GridLayout(row, col));

    add(new Button("Button 1"));

    add(new Button("Button 2"));

    add(new Button("Button 3"));

    add(new Button("Button 4"));

    add(new Button("Button 5"));

    add(new Button("Button 6"));

  }

}

 

GridBagLayout 

 

 

A GridBagLayout aligns components by a rectangular grid of vertical and horizontal cells. 

Each Component can occupy one or more cells (display area). 

The Components can be different sizes.

 

Each Component is associated with an instance of GridBagConstraints.

 

GridBagConstraints hold the values that customize the locations and appearance of each component.

            Alter the values of the constraint variables to alter the display of the components

 

 

GridBagConstraints

 

GridBagConstraints Variables

Layout

Gridx,

Gridy

Leading corner of the display area.

Use:

RELATIVE

Component immediately follows previous Component (along the x axis for gridx or the y axis for gridy)

gridwidth,

gridheight

Specifies the number of cells in a row (for gridwidth)

or column (for gridheight) in the component's display area.

Use:

REMAINDER

Component is the last one in its row (for gridwidth) or column (for gridheight)

RELATIVE

Component is next to last in its row (for gridwidth) or column (for gridheight)

1

Default

Fill

Used when the component's display area is larger than the component's requested size to determine whether (and how) to resize the component

Use:

NONE

No resizing

HORIZONTAL

Make component wide enough to fill its display area

VERTICAL

Make the component tall enough to fill its display area vertically

BOTH

Make the component fill its display area entirely

Ipadx,

Ipady

How much internal padding to add to the minimum size of the component.

The value entered will be multiplied by 2 pixels (for both sides)

insets

How much external padding surrounds the component – minimum amount of space between the component and the edges of its display area. 

anchor

Used when the component is smaller than its display area to determine where (within the display area) to place the component.

Use:  

NORTH, SOUTH, WEST, EAST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST, CENTER

weightx,

weighty

Weight of zero (default) clumps all components into the center of the container.

 

 

 

GridBagLayout Example:

 

 

 import java.awt.*;

 import java.util.*;

 import java.applet.Applet;

 

 public class GridBagEx1 extends Applet {

 

     protected void makebutton(String name,

                               GridBagLayout gridbag,

                               GridBagConstraints c) {

         Button button = new Button(name);

         gridbag.setConstraints(button, c);

         add(button);

     }

 

     public void init() {

         GridBagLayout gridbag = new GridBagLayout();

         GridBagConstraints c = new GridBagConstraints();

 

         setFont(new Font("Helvetica", Font.PLAIN, 14));

         setLayout(gridbag);

 

         c.fill = GridBagConstraints.BOTH;

         c.weightx = 1.0;

         makebutton("Button1", gridbag, c);

         makebutton("Button2", gridbag, c);

         makebutton("Button3", gridbag, c);

 

         c.gridwidth = GridBagConstraints.REMAINDER; //end row

         makebutton("Button4", gridbag, c);

 

         c.weightx = 0.0;          //reset to the default

         makebutton("Button5", gridbag, c); //another row

 

         c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row

         makebutton("Button6", gridbag, c);

 

         c.gridwidth = GridBagConstraints.REMAINDER; //end row

         makebutton("Button7", gridbag, c);

 

         c.gridwidth = 1;        //reset to the default

         c.gridheight = 2;

         c.weighty = 1.0;

         makebutton("Button8", gridbag, c);

 

         c.weighty = 0.0;          //reset to the default

         c.gridwidth = GridBagConstraints.REMAINDER; //end row

         c.gridheight = 1;           //reset to the default

         makebutton("Button9", gridbag, c);

         makebutton("Button10", gridbag, c);

         setSize(300, 100);

     }

 }

 

 

Frame

 

A frame is a top-level window with a title and a border.  A frame may also have scroll bars, a menu bar, etc.

 

 

Frame Constructors

Action

Frame()

Creates a Frame

Frame(String title)

Creates a with given title

Frame Methods

 

setResizable(boolean resizable)

Sets whether this frame is resizable by the user

setTitle(String title)

Sets the title for this Frame

show()

Makes Container visible (Inherited from Window)

addWindowListener(WindowListener l)

Adds the specified window listener to receive window events

 

Frames are capable of generating the following types of WindowEvents:

WINDOW_OPENED

WINDOW_CLOSING

WINDOW_CLOSED

WINDOW_ICONIFIED

WINDOW_DEICONIFIED

WINDOW_ACTIVATED

WINDOW_DEACTIVATED

WINDOW_GAINED_FOCUS

WINDOW_LOST_FOCUS

WINDOW_STATE_CHANGED

 

 

Intro to Events – Calling a Frame from an Applet:               

 

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class FrameExample extends Applet

        implements ActionListener, WindowListener {

    Frame myFrame = new Frame("Entry Test");

    Label reasonLabel =

        new Label("Fill in the fields below, then click OK");

    Label label1 = new Label("User ID:", Label.RIGHT);

    Label label2 = new Label("Password:", Label.RIGHT);

    TextField field1 = new TextField(15);

    TextField field2 = new TextField(15);

    Button OKButton = new Button("OK");

   

    public void init() {

        myFrame.setBackground(Color.white);

        reasonLabel.setFont(new Font("SansSerif", Font.BOLD, 16));

        field2.setEchoChar('*');

        myFrame.add(BorderLayout.NORTH, reasonLabel);

 

        Panel pc = new Panel();

        pc.setLayout(new GridLayout(2,2,8,2));

        pc.add(label1);

        pc.add(field1);

        pc.add(label2);

        pc.add(field2);

        myFrame.add(BorderLayout.CENTER, pc);

 

        Panel ps= new Panel();

        ps.add(OKButton);

        myFrame.add(BorderLayout.SOUTH, ps);

 

        OKButton.addActionListener(this);

        myFrame.addWindowListener(this);

        myFrame.setSize(300,175);

        myFrame.show();

    }

 

    public void actionPerformed(ActionEvent e) {

        myFrame.setVisible(false);        

        myFrame.dispose();

    }

    public void windowActivated(WindowEvent evt)    { }

    public void windowDeactivated(WindowEvent evt)  { }

    public void windowClosed(WindowEvent event)     { }    

    public void windowDeiconified(WindowEvent event){ }    

    public void windowIconified(WindowEvent event)  { }

    public void windowOpened(WindowEvent event)     { }          

    public void windowClosing(WindowEvent event)    {

        myFrame.setVisible(false); 

        myFrame.dispose();

  }  

 

}

 

 

 

Intro to Events – Calling a Frame from an Application:

 

 

import java.awt.*;

import java.awt.event.*;

public class FrameExample2 extends Frame

        implements ActionListener, WindowListener {

    Label reasonLabel =

        new Label("Enter the data needed, then click OK to proceed");

    Label label1 = new Label("User ID:", Label.RIGHT);

    Label label2 = new Label("Password:", Label.RIGHT);

    TextField field1 = new TextField(15);

    TextField field2 = new TextField(15);

    Button OKButton = new Button("OK");

    String name = "";

    String password = "";

   

 

    public FrameExample2() {  // constructor used instead of init()

        super("Sign on Screen");

        setBackground(Color.white);

        reasonLabel.setFont(new Font("SansSerif", Font.BOLD, 16));

        field2.setEchoChar('*');

        add(BorderLayout.NORTH, reasonLabel);

 

        Panel pc = new Panel();

        pc.setLayout(new GridLayout(2,2,8,2));

        pc.add(label1);

        pc.add(field1);

        pc.add(label2);

        pc.add(field2);

        add(BorderLayout.CENTER, pc);

 

        Panel ps= new Panel();

        ps.add(OKButton);

        add(BorderLayout.SOUTH, ps);

 

        OKButton.addActionListener(this);

        addWindowListener(this);

    }

    public static void main(String[] args){  // main added

        FrameExample2 frame = new FrameExample2();

        frame.setSize(400,150);

        frame.show();

    }

 

    public void windowActivated(WindowEvent evt)    { }

    public void windowDeactivated(WindowEvent evt)  { }

    public void windowClosed(WindowEvent event)     { }

    public void windowDeiconified(WindowEvent event){ }

    public void windowIconified(WindowEvent event)  { }

    public void windowOpened(WindowEvent event)     { }    

    public void windowClosing(WindowEvent event)    {

        setVisible(false); 

        dispose();

  }

    public void actionPerformed(ActionEvent e) {

        name = field1.getText();

        password = field2.getText();

        if (name != null)

            System.out.println("Username: " + name

                            + " Password: " + password);

        setVisible(false); 

        dispose();

   }

 

}