0% found this document useful (0 votes)
30 views46 pages

Fepj - 4

Uploaded by

Ankush Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views46 pages

Fepj - 4

Uploaded by

Ankush Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Reference Document

Front End Development & Programming using Java


Applets
An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT
tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining. Applet is a special type of
program that is embedded in the webpage to generate the dynamiccontent. It runs inside the
browser and works at client side.

Important points :
 All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
 Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.
 In general, execution of an applet does not begin at main() method.
 Output of an applet window is not performed by System.out.println(). Rather it is handled
with various AWT methods, such as drawString().

Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.


Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

It is important to understand the order in which the various methods shown in the above image
are called. When an applet begins, the following methods are called, in this sequence:

 init( )

 start( )

 paint( )
When an applet is terminated, the following sequence of method calls takes place:

 stop( )

 destroy( )
Let’s look more closely at these methods.
1. init( ) : The init( ) method is the first method to be called. This is where you should initialize
variables. This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded whereas
start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves
a web page and comes back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn.
This situation can occur for several reasons. For example, the window in which the applet is running
may be overwritten by another window and then uncovered. Or the applet window may be
minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet
must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is
used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is parameterized. It’s
prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing
the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably
running. You should use stop( ) to suspend threads that don’t need to run when the applet is not
visible. You can restart them when start( ) is called if the user returns to the page.

5. destroy( ) : The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory. At this point, you should free up any resources the
applet may be using. The stop( ) method is always called before destroy( ).

How to run an Applet?

There are two ways to run an applet

1. By html file.

2. By appletViewer tool (for testing purpose).


Simple example of Applet By html file

To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First_applet.java
import java.applet.Applet;
import java.awt.Graphics;
public class First_applet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to First Applet creation",150,150);
}
}
/*
<applet code="First_applet.class" width="300" height="300">
</applet> */

OUTPUT :
C:\Reena_JP>set path=C:\Program Files\Java\jdk-7\bin
C:\Reena_JP>javac First_applet.java
C:\Reena_JP>appletviewer First_applet.java
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.


Commonly used methods of Graphics class:

 public abstract void drawString(String str, int x, int y): is used to draw the specified string.

 public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.

 public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
 public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.

 public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.

 public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).

 public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.

 public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.

 public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.

 public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.

 public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.

 Example of Graphics in applet:

 import java.applet.Applet;

 import java.awt.*;

Example :
public class GraphicsDemo extends Applet
{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} }

myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Adding images to an applet


Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax of drawImage() method:
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw
the specified image.
How to get the object of Image:
The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:
public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
public URL getCodeBase(): is used to return the base URL.
Example of displaying image in applet:
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;

public void init() {


picture = getImage(getDocumentBase(),"sonoo.jpg");
}

public void paint(Graphics g) {


g.drawImage(picture, 30,30, this);
}

}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

Adding sound to an applet.


The AudioClip class is used to load and play sound files. To load a sound file
the getAudioClip () Method of the AudioClip class is used. The general form of the getAudioClip ()
method is,
AudioClip getAudioClip (URL pathname, String filename)
AudioClip getAudioClip (URL pathname)
where,
pathname is the address of the sound file. When the image file and the source file are in the same
directory, getCodeBase () method is used as first parameter to the method.

filename is the name of the sound file

Some of the methods of AudioClip class along with their description are listed in Table :
Method Description

void play() used to play the sound for once

void loop() used to play the sound in loop

void stop () used to stop playing the sound

Example: An applet code to demonstrate the use of AudioClip class

import java.applet.*;
import java.awt.*;
public class SoundExample extends Applet
{
private AudioClip mysound;
public void init()
{
mysound=getAudioClip(getCodeBase(), “chimes.wav”);
}
public void start()
{
mysound.loop();
}
public void stop()
{
mysound.stop();
}
The HTML code for SoundExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLETCODE=”SoundExample.class” WIDTH=”200″ HEIGHT=”l30″>
</APPLET>
</CENTER>
</BODY>
</HTML>
Passing parameters to an applet.
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

Event Handling
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
 Foreground Events
 Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of
these events are operating system failures/interrupts, operation completion, etc. As we perform event
handling in AWT or Swing, we can perform it in applet also.

Event Handling : It is a mechanism to control the events and to decide what should happen after an event
occur. To handle the events, Java follows the Delegation Event model. Let's see the simple example of
event handling in applet that prints a message by click on the button.

Example of EventHandling in applet:


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only
once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>

Delegation Event model

 It has Sources and Listeners.

Delegation Event Model

 Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.
 Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.

Registering the Source with Listener

Different Classes provide different registration methods.

Syntax:
addTypeListener()

where Type represents the type of event.

Example 1: For KeyEvent we use addKeyListener() to register.


Example 2:that For ActionEvent we use addActionListener() to register.
Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a component-defined


action occurred like a button click or selecting an
ActionEvent ActionListener item from the menu-item list.

The adjustment event is emitted by an Adjustable


AdjustmentEvent AdjustmentListener object like Scrollbar.

An event that indicates that a component moved, the


ComponentEvent ComponentListener size changed or changed its visibility.

When a component is added to a container (or)


removed from it, then this event is generated by a
ContainerEvent ContainerListener container object.

These are focus-related events, which include focus,


FocusEvent FocusListener focusin, focusout, and blur.

An event that indicates whether an item was


ItemEvent ItemListener selected or not.

An event that occurs due to a sequence of


KeyEvent KeyListener keypresses on the keyboard.

MouseListener & The events that occur due to the user interaction
MouseEvent MouseMotionListener with the mouse (Pointing Device).
Event Class Listener Interface Description

An event that specifies that the mouse wheel was


MouseWheelEvent MouseWheelListener rotated in a component.

TextEvent TextListener An event that occurs when an object’s text changes.

An event which indicates whether a window has


WindowEvent WindowListener changed its status or not.

Different interfaces consists of different methods which are specified below.

Listener Interface Methods

ActionListener
 actionPerformed()

AdjustmentListener
 adjustmentValueChanged()

 componentResized()
 componentShown()
 componentMoved()
ComponentListener
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener
 itemStateChanged()

 keyTyped()
KeyListener
 keyPressed()
Listener Interface Methods

 keyReleased()

 mousePressed()
 mouseClicked()
 mouseEntered()
 mouseExited()
MouseListener
 mouseReleased()

 mouseMoved()
MouseMotionListener
 mouseDragged()

MouseWheelListener
 mouseWheelMoved()

TextListener
 textChanged()

 windowActivated()
 windowDeactivated()
 windowOpened()
 windowClosed()
 windowClosing()
 windowIconified()
WindowListener
 windowDeiconified()

Flow of Event Handling

1. User Interaction with a component is required to generate an event.


2. The object of the respective event class is created automatically after event generation, and it holds all
information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

Code-Approaches
The three approaches for performing event handling are by placing the event handling code in one of the
below-specified places.

1. Within Class
2. Other Class
3. Anonymous Class

Mouse and keyboard events

An event which indicates that a mouse action occurred in a component. A mouse action is
considered to occur in a particular component if and only if the mouse cursor is over the unobscured part
of the component's bounds when the action happens. Component bounds can be obscured by the visible
component's children or by a menu or by a top-level window. This event is used both for mouse events
(click, enter, exit) and mouse motion events (moves and drags).

This low-level event is generated by a component object for:

 Mouse Events
o a mouse button is pressed
o a mouse button is released
o a mouse button is clicked (pressed and released)
o the mouse cursor enters the unobscured part of component's geometry
o the mouse cursor exits the unobscured part of component's geometry
 Mouse Motion Events
o the mouse is moved
o the mouse is dragged

A MouseEvent object is passed to every MouseListener or MouseAdapter object which is


registered to receive the "interesting" mouse events using the component's addMouseListener method.
(MouseAdapter objects implement the MouseListener interface.) Each such listener object gets a
MouseEvent containing the mouse event.
A MouseEvent object is also passed to every MouseMotionListener or MouseMotionAdapter object
which is registered to receive mouse motion events using the component's addMouseMotionListener
method. (MouseMotionAdapter objects implement the MouseMotionListener interface.) Each such
listener object gets a MouseEvent containing the mouse motion event.
When a mouse button is clicked, events are generated and sent to the registered MouseListeners. The
state of modal keys can be retrieved using InputEvent.getModifiers() and InputEvent.getModifiersEx()
. The button mask returned by InputEvent.getModifiers() reflects only the button that changed state,
not the current state of all buttons. (Note: Due to overlap in the values of
ALT_MASK/BUTTON2_MASK and META_MASK/BUTTON3_MASK, this is not always true for
mouse events involving modifier keys). To get the state of all buttons and modifier keys, use
InputEvent.getModifiersEx() . The button which has changed state is returned by getButton().

Adapter classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
Pros of using Adapter classes:
 It assists the unrelated classes to work combinedly.
 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.
 java.awt.event Adapter classes
 Adapter class Listener interface
 WindowAdapter WindowListener
 KeyAdapter KeyListener
 MouseAdapter MouseListener
 MouseMotionAdapter MouseMotionListener
 FocusAdapter FocusListener
 ComponentAdapter ComponentListener
 ContainerAdapter ContainerListener
 HierarchyBoundsAdapter HierarchyBoundsListener
 java.awt.dnd Adapter classes
 Adapter class Listener interface
 DragSourceAdapter DragSourceListener
 DragTargetAdapter DragTargetListener

 javax.swing.event Adapter classes


 Adapter class Listener interface
 MouseInputAdapter MouseInputListener
 InternalFrameAdapter InternalFrameListener

AWT classes

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.Java AWT components are platform-dependent i.e. components
are displayed according to the view of operating system. AWT is heavy weight i.e. its components are
using the resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.

AWT is platform independent?


Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating
API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different look and
feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms
have different view for their native components and AWT directly calls the native subroutine that creates
those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it
will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window. We need to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for
holding the components. It can have other components like button, text field etc. An instance of Panel
class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other
components like button, text field, scrollbar etc. Frame is most widely used container while developing
an AWT application.

Useful Methods of Component Class


Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager Defines the layout manager for the component.
m)

public void setVisible(boolean status) Changes the visibility of the component, by


default false.

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in
AWT.
By extending Frame class (inheritance)
By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
AWTExample1.java
// importing Java AWT class
import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

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

// creating instance of Frame class


AWTExample1 f = new AWTExample1();
}
}
download this example
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets
the position of the awt button.
Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are creating
a TextField, Label and Button component on the Frame.
AWTExample2.java
// importing Java AWT class
import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

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

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
Output:
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 application window. Much of the functionality of
these windows is derived from their parent classes. Thus, a description of the class hierarchies relating to
these two classes is fundamental to their understanding. Figure shows the class hierarchy
for Panel and Frame. Let’s look at each of these classes now.

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. Except for menus, 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. (You already
used many of these methods when you created applets in Chapters 23 and 24.) 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. It does this through the use of various layout managers.

Panel
The Panel class is a concrete subclass of Container. A Panel may be thought of as a recursively nestable,
concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet,
it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar,
menu bar, or border. This is why you don’t see these items when an applet is run inside a browser. 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( ), setPreferredSize( ), 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, you won’t create Window objects directly. Instead, you
will use a subclass of Window called Frame, described next.

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. The precise look of a Frame will differ among environments.
A number of environments are reflected in the screen captures shown throughout this book.

Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other type of
window that you will find valuable: Canvas. Derivedfrom Component, Canvas encapsulates a
blank window upon which you can draw.
working with frame window
In addition to the applet, the type of AWT-based window you will most often create is derived from
Frame. You will use it to create child windows within applets, and top-level or child windows for
stand-alone applications. As mentioned, it creates a standard-style window.
Here are two of Frame’s constructors:
Frame( ) throws HeadlessException Frame(String title) throws HeadlessException
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. Notice that you cannot specify the dimensions of the
window. Instead, you must set the size of the window after it has been created. A
HeadlessException is thrown if an attempt is made to create a Frame instance in an environment
that does not support user interaction.
There are several key methods you will use when working with Frame windows. They are examined
here.
Setting the Window’s Dimensions
The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:
void setSize(int newWidth, int newHeight) 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. One of its forms 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( ), which has this general form: 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. The example in the next section illustrates this technique.
Working with, graphics, colors, font, AWT controls

You might also like