java gui

101
OOM for SE OOM for SE By Prof. Dr. O. P. Vyas Prof. Dr. O. P. Vyas M.Tech.(CS), Ph.D. ( I.I.T. Kharagpur ) DAAD Fellow DAAD Fellow ( Germany ) ( Germany ) AOTS Fellow ( Japan) AOTS Fellow ( Japan)

Upload: iiita

Post on 02-Nov-2014

820 views

Category:

Technology


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: JAVA GUI

OOM for SEOOM for SE

By

Prof. Dr. O. P. VyasProf. Dr. O. P. Vyas M.Tech.(CS), Ph.D. ( I.I.T. Kharagpur )

DAAD Fellow ( Germany )DAAD Fellow ( Germany )

AOTS Fellow ( Japan)AOTS Fellow ( Japan)

Page 2: JAVA GUI

©Silberschatz, Korth and Sudarshan3.2Database System Concepts

Java : GUI & AppletsJava : GUI & Applets

Java GUI

Creating Window: using Frame Using AWT & Swing

Event Handling in Java

Delegation model

Event Source , Listener & Interface Applets & Standalone applications

Writing Applet

Embedding in HTML

Life Cycle of Applet04/08/23 2

Page 3: JAVA GUI

©Silberschatz, Korth and Sudarshan3.3Database System Concepts

OOM & GUI OOM & GUI

Typical GUI providing user friendly environment comprises of ;

Buttons,

Menus

Combo boxes &

Bars: Title Bar, Menu Bar & Scroll Bar.

Although there are several techniques for creating GUI but let us explore GUI creations by Java .

In Java Graphical User Interface (GUI) programming, we do not build GUI components from scratch. Instead we use GUI components provided to us by the JDK. 

04/08/23 3

Page 4: JAVA GUI

©Silberschatz, Korth and Sudarshan3.4Database System Concepts

GUI with JavaGUI with Java

GUI : AWTAWT & SwingSwingCreating Window

Components & Containers

Frame Classes

Layout Managers

Event Handling & Applets Writing Applets

Sandbox Security

04/08/23 4

Page 5: JAVA GUI

©Silberschatz, Korth and Sudarshan3.5Database System Concepts

GUI with JavaGUI with Java

GUI : AWTAWT & SwingSwingCreating Window: GUI Coordinate systems

Import Classes

OOP characteristics on AWT & Swing Instantiate Frame Object

Components & Containers

Frame Classes

Layout Managers

Event Handling & Applets

Sandbox Security

04/08/23 5

Page 6: JAVA GUI

©Silberschatz, Korth and Sudarshan3.6Database System Concepts

User InterfaceUser Interface

Sun had used a logical and object-oriented design for creating a GUI and handling its events.

There are two APIs for creating GUI applications in Java: Swing and AWT (Abstract Windowing Toolkit).

When Java was first released in 1995, it contained a GUI API : AWT.

AWT API contained classes like

Frame to represent a typical window,

Button to represent buttons,

Menu to represent a window’s menu, and so on.

6

Page 7: JAVA GUI

©Silberschatz, Korth and Sudarshan3.7Database System Concepts

GUI: AWT & SwingGUI: AWT & SwingAWT components are referred to as heavyweight components

because their implementation relies heavily on the underlying operating system.

The look and feel of AWT components depend on the platform the program is running on. For example,

an AWT button will look like a Windows button when the program is run on a Windows platform.

The same button will look like a Macintosh button when the program is run on a Macintosh platform.

Swing is different from AWT in that Swing components are 100 percent Java, thereby not relying on the native operating system or platform.

7

Page 8: JAVA GUI

©Silberschatz, Korth and Sudarshan3.8Database System Concepts

AWT & SwingAWT & Swing

Nowadays, most Java GUI programming is done by using Swing.

We will discuss the AWT , though, because it is an important part of GUI programming, and many of the AWT classes are used in Swing, including the layout managers, and event-handling classes and interfaces.

The names of the Swing classes all begin with a capital J, Swing classes all begin with a capital J, like JButton.like JButton.

For the most part, an AWT program can be converted to a Swing program by adding a capital J to the class names used in the source code and recompiling the code.

04/08/23 8

Page 9: JAVA GUI

©Silberschatz, Korth and Sudarshan3.9Database System Concepts

Containers and ComponentsContainers and Components

There are two basic elements of a GUI: containerscontainers and components.components.

A containercontainer is for displaying components, and componentscomponents must be displayed within a container.

A Button is an example of a componentcomponent, whereas a Frame is an example of a container.container.

To display a Button, you place it within a Frame and display the Frame.

04/08/23 9

Page 10: JAVA GUI

©Silberschatz, Korth and Sudarshan3.10Database System Concepts

Swing Components for GUISwing Components for GUI

10

Object

Component

Container

The Class Hierarchy depicts that from where Swing components inherit their common attributescommon attributes and behavior.

Class Component ( package.java.awt) is subclass of Object that declares many of the attributes and behaviors common to GUI Component

JComponentThe Swing API uses many of the AWT classes Swing API uses many of the AWT classes and interfaces.

Page 11: JAVA GUI

©Silberschatz, Korth and Sudarshan3.11Database System Concepts

Creating Window: using FrameCreating Window: using Frame

Every GUI app uses what is called a Frame that comes with the JDK. 

A Frame is a window with borders, a title bar, and buttons for closing and maximizing or minimizing itself. 

It also knows how to resize itself. 

Every GUI app subclasses Frame in some way to add more functionalities to the window frame. 

One common task is to tell the system to terminate all "threads" of the GUI app when the user clicks on the exit (close) button of the main GUI window. 

04/08/23 11

Page 12: JAVA GUI

©Silberschatz, Korth and Sudarshan3.12Database System Concepts

Creating Window Creating Window

The basic starting point of a GUI is the container because you need a container before you can start laying out your components.

The java.awt.Frame and javax.swing.JFrame classes are containers that represent a basic window with a title bar and common windowing capabilities such as resizing, minimizing, maximizing, and closing.

The Frame class is used for AWT programs and is the parent class of JFrame, which is used for Swing programs.

04/08/23 12

Page 13: JAVA GUI

©Silberschatz, Korth and Sudarshan3.13Database System Concepts

GUI CoordinatesGUI Coordinates

All components and containers have a size and location, which is denoted in pixels.

A pixel is a relative unit of measurement based on the settings of the user’s screen.

The pixels create a coordinate system, with the upper-left corner of the screen as the origin (0,0).

Any point on the screen can be represented as an (x,y) value, where x is the number of pixels to the right of the origin, and y is the number of pixels down from the origin.

04/08/23 13

Page 14: JAVA GUI

©Silberschatz, Korth and Sudarshan3.14Database System Concepts

Using FrameUsing Frame

For example, the point (100,100) is 100 pixels over and 100 pixels down from the upper-left corner of the screen.

Suppose that a Frame is instantiated and given the bounds (100,100, 300, 400):

Frame f = new Frame();

f.setBounds(100, 100, 300, 400);

The upper-left corner of the Frame is the point (100,100) relative to the computer screen.

The width of this Frame is 300 and the height is 400, so the lower-right corner of the Frame is the point (400, 500) of the computer screen

04/08/23 14

Page 15: JAVA GUI

©Silberschatz, Korth and Sudarshan3.15Database System Concepts

GUI Coordinate systemGUI Coordinate system

There is another coordinate system of GUI components referred to as the relative coordinate system. relative coordinate system.

The The relative coordinate system relative coordinate system is based is based on the upper-left corner of the container that the component is residing in.

The upper-left corner of a container is an origin (0,0), and components are placed in a container relative to the container’s origin, not the screen’s origin.

For example, the following statements instantiate a Button, assign it bounds (20, 200, 60, 40). The Button is then added to the Frame object instantiated earlier:

Button ok = new Button(“OK”);Button ok = new Button(“OK”);

ok.setBounds(20, 200, 60, 40);ok.setBounds(20, 200, 60, 40);

f.add(okf.add(ok); //Add the Button to a Frame

04/08/23 15

Page 16: JAVA GUI

©Silberschatz, Korth and Sudarshan3.16Database System Concepts

CoordinatesCoordinates

The upper-left corner of the OK button appears 20 pixels over and 200 pixels down from the upper-left corner of the Frame. The size of the Button is 60 pixels wide and 40 pixels high.

Assuming that Frame f has not been moved, this puts the Button 120 pixels over and 300 pixels down from the upper-left corner of the screen. This point changes if the Frame is moved. However, the relative location of the Button within the Frame does not move, even if the Frame moves. This is the desired result of GUI containers and components.

When we move a window, we expect all the components within the window to move along with it. Therefore, we rarely concern ourselves with the actual screen coordinates of a component.

The component’s relative coordinates are what are important to a programmer laying out components in a container.

04/08/23 16

Page 17: JAVA GUI

©Silberschatz, Korth and Sudarshan3.17Database System Concepts

java.awt.Frame Classjava.awt.Frame Class

When working with Frame objects, there are basically three steps involved to get a Frame window to appear on the screen:

1. Instantiate the Frame object in memory.

2. Give the Frame object a size using setSize(), setBounds(), or pack().

3. Make the Frame appear on the screen by invoking setVisible(true).

04/08/23 17

Page 18: JAVA GUI

©Silberschatz, Korth and Sudarshan3.18Database System Concepts

Instantiate the Frame ObjectInstantiate the Frame Object

The java.awt.Frame java.awt.Frame class has four constructors:

I. public Frame(). Creates a new frame with no message in the title bar.

II. public Frame(String title). Creates a new frame with the given String appearing in the title bar.

III. public Frame(GraphicsConfiguration gc). Creates a frame with the specified GraphicsConfiguration of a screen device.

IV. public Frame(String title, GraphicsConfiguration gc). Creates a frame with the specified title and GraphicsConfiguration.

04/08/23 18

Page 19: JAVA GUI

©Silberschatz, Korth and Sudarshan3.19Database System Concepts

Instantiate Frame ObjectInstantiate Frame Object

Each of the preceding constructors creates a new Frame object that is initially invisible and has a size of 0 pixels size of 0 pixels wide and 0 pixels highwide and 0 pixels high.

The String passed in to a Frame constructor String passed in to a Frame constructor appears in the title bar, and the Graphics-Configuration represents where the image is to be displayed.

If you do not pass in a GraphicsConfiguration object, your Frame will use the default graphics destination, which in Windows is the computer screen.

The following statement demonstrates instantiating a new Frame object in memory:

Frame f = new Frame(“My first window”);Frame f = new Frame(“My first window”);

04/08/23 19

Page 20: JAVA GUI

©Silberschatz, Korth and Sudarshan3.20Database System Concepts

WindowsWindows This Frame is not displayed on the screen, and it has an initial size

of 0 by 0.

We need to give our Frame a size before displaying it, which can be done by invoking one of the following five methods:

public void setSize(int width, int height). Sets the size of the Frame to the given width and height, in pixels.

public void setSize(java.awt.Dimension d). Sets the size of the Frame to the same width and height as the given Dimension object.

public void setBounds(int x, int y, int width, int height). Sets both the size and initial location of the window, where x represents the number of pixels over from the upper-left corner of the screen, and y represents the number of pixels down from the upper-left corner of the screen.

public void setBounds(java.awt.Rectangle r). Sets the bounds of the Frame to that of the given Rectangle.

public void pack(). Sets the size of the Frame to be just big enough to display all its components with their preferred size.

04/08/23 20

Page 21: JAVA GUI

©Silberschatz, Korth and Sudarshan3.21Database System Concepts

Create WindowCreate Window After we have

instantiated a Frame,

given it a size, and

laid out the components within it, we display the Frame on the screen by

invoking the setVisible() method setVisible() method inherited from the Component class.

The signature of setVisible() is:

public void setVisible(boolean show)public void setVisible(boolean show)

If the boolean passed in is true, the component is made visible. If the value is false, the component is hidden.

04/08/23 21

Page 22: JAVA GUI

©Silberschatz, Korth and Sudarshan3.22Database System Concepts

FrameDemo programFrameDemo program

The following FrameDemo program creates a Frame object, sets its bounds, and displays it on the screen.

Study the program and try to determine its output,

import java.awt.*;import java.awt.*;

public class FrameDemopublic class FrameDemo

{{

public static void main(String [] args)public static void main(String [] args)

{{

Frame f = new Frame(“My first window”);Frame f = new Frame(“My first window”);

f.setBounds(100,100, 400, 300);f.setBounds(100,100, 400, 300);

f.setVisible(true);f.setVisible(true);

}}

}}

04/08/23 22

Page 23: JAVA GUI

©Silberschatz, Korth and Sudarshan3.23Database System Concepts

WindowWindow

04/08/23 23

We can move, resize, minimize, and maximizethe Frame window.

However, we can’t close the window because closinga window often implies ending the program.

If the user needs to save adocument or other settings before ending, your program needs a chance

to do this.The closing involves handling the WindowEventWindowEvent generated by a user attempting

toclose the window.

Page 24: JAVA GUI

©Silberschatz, Korth and Sudarshan3.24Database System Concepts

Creating Window with SwingCreating Window with Swing

Let’s look at the steps involved in creating a JFrame. You start by instantiating a JFrame using one of the following constructors:

public JFrame(). Creates a new JFrame with no message in the title bar.

public JFrame(String title). Creates a new JFrame with the given String appearing in the title bar.

public JFrame(GraphicsConfiguration gc). Creates a JFrame with the specified GraphicsConfiguration of a screen device.

public JFrame(String title, GraphicsConfiguration gc). Creates a Jframe with the specified title and GraphicsConfiguration.

24

Page 25: JAVA GUI

©Silberschatz, Korth and Sudarshan3.25Database System Concepts

The constructors are similar to those in the Frame class, and the parameters have the same uses. The following statement instantiates a JFrame with “My first JFrame” in the title bar:

JFrame f = new JFrame(“My first JFrame”);

As with Frame objects, this JFrame is initially not visible and has a size of 0 pixels by 0 pixels.

You invoke one of the setSize(), setBounds(), or pack() methods to give the JFrame a size and then invoke setVisible() to make it visible.

04/08/23 25

Page 26: JAVA GUI

©Silberschatz, Korth and Sudarshan3.26Database System Concepts

The following JFrameDemo program demonstrates creating and displaying a JFrame object.

import javax.swing.*;import javax.swing.*;

public class JFrameDemopublic class JFrameDemo

{{

public static void main(String [] args)public static void main(String [] args)

{{

JFrame f = new JFrame(“My first JFrame”);JFrame f = new JFrame(“My first JFrame”);

f.setSize(400, 300);f.setSize(400, 300);

f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

f.setVisible(true);f.setVisible(true);

}}

}}

04/08/23 26

Page 27: JAVA GUI

©Silberschatz, Korth and Sudarshan3.27Database System Concepts

Using SwingUsing Swing

04/08/23 27

Clicking the X in the title bar of a JFrame causes the window to be hiddenby default, but this does not cause your program to stop executing.

Weneed to press Ctrl+c at the command prompt to stop the JVM, even though

our JFrame is no longer visible on the screen.

Page 28: JAVA GUI

©Silberschatz, Korth and Sudarshan3.28Database System Concepts

04/08/23 28

Page 29: JAVA GUI

©Silberschatz, Korth and Sudarshan3.29Database System Concepts

Containers and ComponentsContainers and Components

There are two basic elements of a GUI: containerscontainers and components.components.

A container is for displaying components, and components must be displayed within a container.

A Button is an example of a component, whereas a Frame is an example of a container.

To display a Button, you place it within a Frame and display the Frame.

04/08/23 29

Page 30: JAVA GUI

©Silberschatz, Korth and Sudarshan3.30Database System Concepts

GUI GUI

Component is an abstract class that is the parent class of the various GUI components of the AWT: Button, Checkbox, Choice, Label, List, and Text- Component.

Container is an abstract class that is the parent class of the containers of the AWT: Window, Panel, and ScrollPane.

Child objects of ComponentComponent are placed within child objects of Container.

For example, a ButtonButton can be placed within a Panel, or a List can be placed within a FrameFrame.

04/08/23 30

Page 31: JAVA GUI

©Silberschatz, Korth and Sudarshan3.31Database System Concepts

Adding Components to a ContainerAdding Components to a Container

AComponent is added to a Container using one of the following add() methods found in the java.awt.Container class:

public Component add(Component c). Adds the Component to the Container and returns a reference to the newly added Component.

public Component add(Component c, int index). Adds the Component to the Container at the position specified by index

public Component add(Component c, Object constraints). Adds the Component to the Container using the specified constraints

04/08/23 31

Page 32: JAVA GUI

©Silberschatz, Korth and Sudarshan3.32Database System Concepts

ComponentsComponents

To demonstrate using the add() method, the following AddDemo program creates a Frame object and adds a Button.

import java.awt.*;

public class AddDemo

{

public static void main(String [] args)

{

Frame f = new Frame(“A simple window”);

Button cancel = new Button(“Cancel”);

f.add(cancel); //Add the Button to the Frame

f.setSize(100,100);

f.setVisible(true);

}

}

04/08/23 32

Page 33: JAVA GUI

©Silberschatz, Korth and Sudarshan3.33Database System Concepts

04/08/23 33

Notice that the cancel Button is added to the Frame f. Whenever f is displayed,

the cancel button is also displayed

Notice that the Button consumes the entire interior consumes the entire interior of theFrame, no matter what size we make the Frame.

Page 34: JAVA GUI

©Silberschatz, Korth and Sudarshan3.34Database System Concepts

Using JframeUsing Jframe Components are added to a JFrame differently from the way they

are added to a Frame. When using a Frame, you invoke the add() method directly on the Frame object, adding the components directly to the Frame.

When using a JFrame, we still invoke the add() method, but not on the JFrame. Instead, we add the components to the content pane of the JFrame by invoking the add() method on the JFrame’s content pane.

We use the getContentPane() method in the JFrame class to obtain a reference to the content pane of a JFrame. For Ex, the following statements add a JButton to the content pane of a JFrame:

JFrame f = new JFrame();

JButton b = new JButton();

Container contentPane = f.getContentPane();

contentPane.add(b);

04/08/23 34

Page 35: JAVA GUI

©Silberschatz, Korth and Sudarshan3.35Database System Concepts

Notice that the return value of getContentPane() is Container. The add() method is invoked on the content pane, adding b by using the layout manager of the content pane.

It involves the concept of a Layout manager.

A container uses a layout manager to determine how components are laid out within the container.

The Frame class uses a BorderLayout manager by default, and the BorderLayout manager has placed the Button in the center of the Frame.

04/08/23 35

Page 36: JAVA GUI

©Silberschatz, Korth and Sudarshan3.36Database System Concepts

Suppose GUI programming using Visual Basic, and all one could visually place the components exactly where I wanted them in the window using the Visual Basic IDE. Can you do that in Java?

A: You can if you have an IDE like Visual Café or Visual Age. These IDEs have GUI editors that let you place components exactly where you want them. You can also organize components by assigning a null layout manager to your container and specifying the exact location and size of each component added.

Q: So why would you ever use one of the layout managers? Why not just use the IDE or lay out the components exactly where you want them?

A: Two reasons: First, you might not have an IDE, and if you do, there is a certain complexity to figuring out how to use it. If you understand layout managers, this will help you comprehend the code that the IDE is generating for you.

Second, using a layout manager to lay out your components makes your GUI more portable. You might be surprised to see that a GUI that you created using an IDE looks great on Windows, but not so great on a Unix or Macintosh platform. The same problem can occur if you try to lay out components exactly where you want them..

Page 37: JAVA GUI

©Silberschatz, Korth and Sudarshan3.37Database System Concepts

Java GUI : Ques.Java GUI : Ques.

Q: How does the layout manager know how you want your GUI to look?

A: You need to understand the way each type of layout manager behaves. For example, you need to know that the FlowLayout manager gives components their preferred size, and that BorderLayout places components in specific regions of the container.

By using the different layout managers and nesting containers, you have great control over the look of the GUI, while at the same time letting the layout managers determine the exact location and size of your GUI components.

Page 38: JAVA GUI

©Silberschatz, Korth and Sudarshan3.38Database System Concepts

Layout ManagersLayout Managers

A container uses a layout manager to determine both the location and size of the components within the container. A container can be assigned one layout manager, which is done using the setLayout() method of the java.awt.Container class:

public void setLayout(LayoutManager m)

LayoutManager is an interface that all the layout managers’ classes must implement.

You can create your own layout manager by writing a class that implements the methods of the LayoutManager interface (no small task), or

04/08/23 38

Page 39: JAVA GUI

©Silberschatz, Korth and Sudarshan3.39Database System Concepts

We can use one of the many layout managers of the AWT and Swing APIs, including the following:

java.awt.FlowLayout. Lays out components in a left-to-right flow, with each component given its preferred size. A Panel has FlowLayout by default.

java.awt.BorderLayout. Divides a container into five regions, allowing one component to be added to each region. A Frame and the content pane of a JFrame have BorderLayout by default.

java.awt.GridLayout. Divides a container into a grid of rows and columns, with one component added to each region of the grid and each component having the same size.

java.awt.GridBagLayout. Divides a container into regions similar to GridLayout, except that components do not need to be the same size. Components can span more than one row or column.

39

Page 40: JAVA GUI

©Silberschatz, Korth and Sudarshan3.40Database System Concepts

java.awt.CardLayout. Each component added to the container is treated as a card, with only one card being visible at a time (similar to a deck of cards).

javax.swing.BoxLayout. Allows components to be laid out vertically or horizontally. BoxLayout is similar to GridBagLayout, but it is generally easier to use.

javax.swing.SpringLayout. Lays out components with a specified distance between the edges of each component.

javax.swing.OverlayLayout. Displays components over the top of each other, similarly to CardLayout. This is a useful layout manager for creating tabbed panes.

04/08/23 40

Page 41: JAVA GUI

©Silberschatz, Korth and Sudarshan3.41Database System Concepts

Any container can use any layout manager. Notice that Frame objects and the content pane of JFrame objects have BorderLayout by default.

However, you can assign them any layout manager you need. Similarly, Panel objects have FlowLayout by default, but a Panel can be assigned any other layout manager.

There are more commonly used ones, including FlowLayout, BorderLayout, GridLayout, and BoxLayout

04/08/23 41

Page 42: JAVA GUI

©Silberschatz, Korth and Sudarshan3.42Database System Concepts

FlowLayout ManagerFlowLayout Manager

The java.awt.FlowLayout class represents a layout manager that aligns components in a left-to-right flow, such as words in a sentence.

FlowLayout has the following properties:

Components are given their preferred size.

■■ The order in which the components are added determines their order in the container. The first component added appears to the left, and subsequent components flow in from the right.

■■ If the container is not wide enough to display all of the components, the components wrap around to a new line.

■■ You can control whether the components are centered, left-justified, or right-justified.

■■ You can control the vertical and horizontal gap between components.

04/08/23 42

Page 43: JAVA GUI

©Silberschatz, Korth and Sudarshan3.43Database System Concepts

To use FlowLayout in a Frame or JFrame, you need to invoke setLayout() on the container and pass in a new FlowLayout object. The FlowLayout class has three constructors:

public FlowLayout(). Creates a new FlowLayout that centers the components with a horizontal and vertical gap of five units (where the unit is pixels in most GUI operating systems).

public FlowLayout(int align). Creates a FlowLayout object with the specified alignment, which is one of the following values: FlowLayout .CENTER, FlowLayout.RIGHT, or FlowLayout.LEFT. The horizontal and vertical gap between components is five units.

public FlowLayout(int align, int hgap, int vgap). Creates a FlowLayout object with the specified alignment, horizontal gap, and vertical gap.

04/08/23 43

Page 44: JAVA GUI

©Silberschatz, Korth and Sudarshan3.44Database System Concepts

For example, the following statement instantiates a new FlowLayout manager that justifies components to the right. The horizontal and vertical gap is not specified, so they will have the default value of 5.

Frame f = new Frame();

f.setLayout(new FlowLayout(FlowLayout.RIGHT));

The FlowLayoutDemo program creates a Frame and assigns it FlowLayout. Components are then added using the add() method.

Study the program and see if you can determine its output, which is shown.

04/08/23 44

Page 45: JAVA GUI

©Silberschatz, Korth and Sudarshan3.45Database System Concepts

import java.awt.*;

public class FlowLayoutDemo

{

public static void main(String [] args)

{

Frame f = new Frame(“FlowLayout demo”);

f.setLayout(new FlowLayout());

f.add(new Button(“Red”));

f.add(new Button(“Blue”));

f.add(new Button(“White”));

List list = new List();

for(int i = 0; i < args.length; i++)

{

list.add(args[i]);

}

f.add(list);

f.add(new Checkbox(“Pick me”, true));

f.add(new Label(“Enter name here:”));

f.add(new TextField(20));

f.pack();

f.setVisible(true);

}

}

04/08/23 45

Page 46: JAVA GUI

©Silberschatz, Korth and Sudarshan3.46Database System Concepts

Flowlayout demoFlowlayout demo

The FlowLayoutDemo demonstrates using some of the AWT components.

Three Button components are added to the Frame first. Then, a List is created, filled with the command-line arguments, and added to the Frame. Next, a Checkbox, Label, and TextField are added. The pack() method sizes the Frame so all the components fit nicely, as you can see by the output

04/08/23 46

Page 47: JAVA GUI

©Silberschatz, Korth and Sudarshan3.47Database System Concepts

04/08/23 47

Page 48: JAVA GUI

©Silberschatz, Korth and Sudarshan3.48Database System Concepts

Applets & Event HandlingApplets & Event Handling Event Handling in Java

Delegation modelEvent Source , Listener & Interface

Using AWT & Swing

Applets & Standalone applications

Using JAR files in Java

Writing Applet Sandbox Security & HTML Intro.

HelloWorldApplet Class & Event Handling in Applet

Embedding in HTML

Life cycle of an Applet: Life Cycle methods

Playing Audio with Java Applet04/08/23 48

Page 49: JAVA GUI

©Silberschatz, Korth and Sudarshan3.49Database System Concepts

Swing Components for GUISwing Components for GUI

49

Object

Component

Container

The Class Hierarchy depicts that from where Swing components inherit their common attributescommon attributes and behavior.

Class Component ( package.java.awt) is subclass of Object that declares many of the attributes and behaviors common to GUI Component

JComponentThe Swing API uses many of the AWT classes Swing API uses many of the AWT classes and interfaces.

Page 50: JAVA GUI

©Silberschatz, Korth and Sudarshan3.50Database System Concepts

Event handlingEvent handling Normally a user interacts with an application’s GUI to indicate the tasks

that the application should perform.

When you write an e-mail in the email software, clicking the SendSend button tells the application to send the email to the specified email addresses.

When the user interacts with a GUI component the interaction- known as an eventan event-drives the program to perform a task.

Some common events (user-interactions) that might cause an application to perform a task include;

clicking a button,

typing in a text field,

selecting an item from a menuselecting an item from a menu,

closing a window

moving the mouse. The code that performs a task in response to an event is called an event

handler and the overall process of responding to events is known as event handling.

50

Page 51: JAVA GUI

©Silberschatz, Korth and Sudarshan3.51Database System Concepts

Event Handling & GUIEvent Handling & GUI GUI programs discussed so far do not have any

functionality beyond looking good.

We are required to understand how to create GUI components and how to handle their events.

Now we will discuss the delegation model, the architecture behind event handling in Java.

We will then look at the various components of the AWT and Swing APIs, discussing how to create them and how to handle their events.

Java GUI programming uses the Delegation Model for handling the events of components and containers.

The sourcesource of an event invokes a method on a registered registered listener listener of the event, with the two objects communicating via a common interface.

51

Page 52: JAVA GUI

©Silberschatz, Korth and Sudarshan3.52Database System Concepts

The Delegation ModelThe Delegation Model Events in Java are fired and handled using a design known as the

delegation model.

With the delegation model, a source generates an event and a listenerlistener handles it, creating an object-oriented approach to handling events. (A class is written to handle the events of a component.)

There are 03 players in delegation model:-

1)1) The source of the eventThe source of the event. In GUI programming, the component is the source of the event. Events are Java objects that are instantiatedinstantiated by the component and passed as an argument to any listeners.

2)2) An event listenerAn event listener. A listener of an event registers itself with the source of the event. When an event occurs, the source of the event invokes a method on the listener.

3)3) An interfaceAn interface. The interface contains the methods that the listener must implement and that the source of the event invokes when the event occurs.

04/08/23 52

Page 53: JAVA GUI

©Silberschatz, Korth and Sudarshan3.53Database System Concepts

Event Handling & AppletEvent Handling & Applet

An applet is a Java program that runs in a Web browser.

An applet can be a fully functional Java application because it has the entire Java API at its disposal.

Writing an applet is similar to creating a graphical user interface (GUI) program, because an applet is a Container object.

Containers, Components, Layout managers, and event handling are a big part of developing applets.

04/08/23 53

Page 54: JAVA GUI

©Silberschatz, Korth and Sudarshan3.54Database System Concepts

AppletsApplets

An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run.

An applet is typically embedded inside a web page and runs in the context of a browser.

An applet must be a subclass of the java.applet.Applet class.

The Applet class provides the standard interface between the applet and the browser environment.

Swing provides a special subclass of the Applet class called javax.swing.JApplet.

The JApplet class should be used for all applets that use Swing components to construct their graphical user interfaces (GUIs).

54

Page 55: JAVA GUI

©Silberschatz, Korth and Sudarshan3.55Database System Concepts

AppletsAppletsThere are some important differences between an applet an applet and a

standalone Java standalone Java application, including the following:

An applet is a Java class that extends the java.applet.Applet class.

A main() method is not invoked on an applet, and an applet class will (typically) not define main().

Applets are designed to be embedded within an HTML page.

When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user’s machine.

A user must have a JVM on his or her machine. The JVM can be either a plug-in of the Web browser or a separate runtime environment.

The JVM on the user’s machine creates an instance of the applet class and invokes various methods during the applet’s lifetime.

55

Page 56: JAVA GUI

©Silberschatz, Korth and Sudarshan3.56Database System Concepts

Truly Platform independentTruly Platform independent Applets have strict security rules that are enforced by the Web

browser. The security of an applet is often referred to as sandbox sandbox securitysecurity, comparing the applet to a child playing in a sandbox with various rules that must be followed.

Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Because applets are a part of a Web page, however, they can be accessed by any Web browser using any operating system on any device, and therefore can be executed on many different platforms and devices.

I can run an applet using Windows XP and Internet Explorer, and you can run the same applet on a Macintosh running Netscape Navigator.

We will see how to write an applet and embed it in an HTMLpage.

04/08/23 56

Page 57: JAVA GUI

©Silberschatz, Korth and Sudarshan3.57Database System Concepts

Sandbox SecuritySandbox Security Applets run in a Web browser restricted to a set of security

policies referred to as sandbox security.

The purpose of the sandbox security model is to ensure that the applet you are downloading and executing is not going to not going to do terrible things to your computer. do terrible things to your computer.

This is especially important in today’s Internet world of viruses and other undesirable side effects of software applications.

Applets that are downloaded and executed in a Web browser must adhere to the following rules:

An applet An applet cannot access any files cannot access any files on a user’s operating system.on a user’s operating system.

An applet An applet can only create network connections can only create network connections to the applet’s code to the applet’s code base, and cannot connect to other network addresses.base, and cannot connect to other network addresses.

An applet An applet cannot execute a program on the user’s machinecannot execute a program on the user’s machine..

An applet An applet cannot access system information cannot access system information or use system dialog or use system dialog boxes such the Open File or Print dialog boxes.boxes such the Open File or Print dialog boxes.

04/08/23 57

Page 58: JAVA GUI

©Silberschatz, Korth and Sudarshan3.58Database System Concepts

Using JAR files in JavaUsing JAR files in Java The J2SDK comes with a tool called jar for creating JAR (Java

ARchive) files.

JAR files are used in all aspects of Java, and the further you progress in your Java programming, the more you will realize that JAR files are everywhere.

The reason they are so widely used is because both Java compilers and JVMs can read files from a JAR without requiring the JAR file to be uncompressed.

You can take the largest of Java applications, consisting of any number of .class files, and compress all these files into a single JAR file.

Your application can then be deployed by simply giving someone the JAR file, and they do not even have to uncompress it to execute it.

It is no surprise, therefore, that JAR files are a common aspect of applets.

04/08/23 58

Page 59: JAVA GUI

©Silberschatz, Korth and Sudarshan3.59Database System Concepts

Playing Audio using Java AppletsPlaying Audio using Java Applets

Java has the feature of playing the sound file.

We can see how to play a audio clip in our java applet viewer or on the browser.

An applet can play an audio file represented by the AudioClip interface in the java.applet packagejava.applet package.

The AudioClip interface has three methods to get an Audio file play, stop play, stop or replay the Audio file.

Many sites detailing audio features of Java

applets are there :

http://javaboutique.internet.com/audio/http://javaboutique.internet.com/audio/

04/08/23 59

Page 60: JAVA GUI

©Silberschatz, Korth and Sudarshan3.60Database System Concepts

Delegation Model Delegation Model & &

Working of Java Applet Working of Java Applet

04/08/23 60

Page 61: JAVA GUI

©Silberschatz, Korth and Sudarshan3.61Database System Concepts

Delegation ModelDelegation Model

The Delegation model delegates an event’s processing to the Event listener.

Many different type of event can occur when the user interacts with a GUI.

The information about any GUI event that occurs is stored in an object of a class that extends AWTEvent

Next page illustrates a hierarchy containing many event classes from the package java.awt.event.

These event types are used with both AWT Swing components.

04/08/23 61

Page 62: JAVA GUI

©Silberschatz, Korth and Sudarshan3.62Database System Concepts

Some Event classes of package java.awt.eventSome Event classes of package java.awt.event

04/08/23 62

Page 63: JAVA GUI

©Silberschatz, Korth and Sudarshan3.63Database System Concepts

Event handlingEvent handling

For example, when a user clicks a java.awt.ButtonButton, the Button generates a java.awt.event.ActionEventActionEvent.

The Button invokes the actionPerformed() actionPerformed() method on each registered listener of the Button, passing in the ActionEvent objectActionEvent object.

The actionPerformed() actionPerformed() method is defined in the java.awt.event.ActionListener interface, which each listener must implement.

In this scenario, the Button is the source of the event, the interfaceinterface is ActionListener, and the listener is any class any class that implements ActionListener and registersregisters itself with the Button.

04/08/23 63

Page 64: JAVA GUI

©Silberschatz, Korth and Sudarshan3.64Database System Concepts

Events handling : Ques.Events handling : Ques.

Q: How do you register a listener with a Button?

A: Two steps are involved. You first need to write a class that implements ActionListener. You then invoke the addActionListener() method on the Button, passing in an instance of your class.

Q: So do all components generate an ActionEvent?

A: No. There are many types of events, and each event has a corresponding listener interface. For example, windows generate WindowEvent objects and invoke a method from the WindowListener interface. A check box generates an ItemEvent and invokes a method in the ItemListener interface.

Page 65: JAVA GUI

©Silberschatz, Korth and Sudarshan3.65Database System Concepts

Event Listener InterfacesEvent Listener Interfaces

Java uses a standard naming convention for event classes and listener interfaces:

The name of the event class uses the convention <Name>Event, and

the corresponding listener interface uses the convention <Name>Listener.

For example, the ActionEvent class is associated with the one method of the ActionListener interface, and the WindowEvent class is associated with the seven methods of the WindowListener interface.

04/08/23 65

Page 66: JAVA GUI

©Silberschatz, Korth and Sudarshan3.66Database System Concepts

The event listener interface contains the methods that the event source invokes on the listener,

And it provides the means of communication between the source of the event and the listener of the event.

Each type of event has a corresponding listener interface.

An event listener interface extends the java.util.EventListener interface.

The EventListener interface does not contain any methods, but is used for tagging an event listener interface for use with the delegation model of event handling.

04/08/23 66

Page 67: JAVA GUI

©Silberschatz, Korth and Sudarshan3.67Database System Concepts

Event listener interfaceEvent listener interface

For example, the ActionListener interface is defined as:

package java.awt.event;

public interface ActionListener extends java.util.EventListener

{

public void actionPerformed(ActionEvent e);

}

Notice that ActionListener extends EventListener and is in the java.awt.event package, which is where all the AWT event classes and listener interfaces are defined.

The javax.swing.event package contains the event classes and listener interfaces unique to Swing.

The AWT components only generate AWT events, while Swing components generate both AWT and Swing events.

04/08/23 67

Page 68: JAVA GUI

©Silberschatz, Korth and Sudarshan3.68Database System Concepts

04/08/23 68

Page 69: JAVA GUI

©Silberschatz, Korth and Sudarshan3.69Database System Concepts

AppletsApplets

An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run.

An applet is typically embedded inside a web page and runs in the context of a browser.

An applet must be a subclass of the java.applet.Applet class.

The Applet class provides the standard interface between the applet and the browser environment.

Swing provides a special subclass of the Applet class called javax.swing.JApplet.

The JApplet class should be used for all applets that use Swing components to construct their graphical user interfaces (GUIs).

69

Page 70: JAVA GUI

©Silberschatz, Korth and Sudarshan3.70Database System Concepts

AppletsAppletsThere are some important differences between an applet an applet and a

standalone Java standalone Java application, including the following:

An applet is a Java class that extends the java.applet.Applet class.

A main() method is not invoked on an applet, and an applet class will (typically) not define main().

Applets are designed to be embedded within an HTML page.

When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user’s machine.

A user must have a JVM on his or her machine. The JVM can be either a plug-in of the Web browser or a separate runtime environment.

The JVM on the user’s machine creates an instance of the applet class and invokes various methods during the applet’s lifetime.

70

Page 71: JAVA GUI

©Silberschatz, Korth and Sudarshan3.71Database System Concepts

Truly Platform independentTruly Platform independent Applets have strict security rules that are enforced by the Web browser.

The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.

Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Because applets are a part of a Web page, however, they can be accessed by any Web browser using any operating system on any device, and therefore can be executed on many different platforms and devices.

I can run an applet using Windows XP and Internet Explorer, and you can run the same applet on a Macintosh running Netscape Navigator.

We will see how to write an applet and embed it in an HTMLpage.

This will involve writing some HTML, so basics will be reqd.

JAR files will also be discussed in detail because they are important aspects of applets.

04/08/23 71

Page 72: JAVA GUI

©Silberschatz, Korth and Sudarshan3.72Database System Concepts

Sandbox SecuritySandbox Security

Applets run in a Web browser restricted to a set of security policies referred to as sandbox security.

The purpose of the sandbox security model is to ensure that the applet you are downloading and executing is not going to do terrible things to your computer.

This is especially important in today’s Internet world of viruses and other undesirable side effects of software applications.

Applets that are downloaded and executed in a Web browser must adhere to the following rules:

An applet cannot access any files on a user’s operating system.An applet cannot access any files on a user’s operating system.

An applet can only create network connections to the applet’s code An applet can only create network connections to the applet’s code base, and cannot connect to other network addresses.base, and cannot connect to other network addresses.

An applet cannot execute a program on the user’s machine.An applet cannot execute a program on the user’s machine.

An applet cannot access system information or use system dialog An applet cannot access system information or use system dialog boxes such the Open File or Print dialog boxes.boxes such the Open File or Print dialog boxes.

04/08/23 72

Page 73: JAVA GUI

©Silberschatz, Korth and Sudarshan3.73Database System Concepts

Sandbox SecuritySandbox Security An applet can be granted permission to leave the sandbox

and perform an otherwise restricted operation.

For example, you can grant an applet permission to access files on your local hard drive.

Of course, you will want to make sure you trust the source of the applet before granting such permission.

An applet can also be signed, which involves creating a security certificate.

This is the typical way to create an applet that needs to perform tasks outside the sandbox because it provides the user of the applet with some assurance as to the source of the applet, letting the user decide whom he or she trusts. Creating a certificate and associating permissions with it are

beyond the scope & for more information, check Sun’s Java Web site at http://java.sun.com/.

04/08/23 73

Page 74: JAVA GUI

©Silberschatz, Korth and Sudarshan3.74Database System Concepts

Q: How does the sandbox enforce these rules?

A: The security permissions are enforced by the JVM.

Q: Suppose a programmer familiar with Java security writes an applet that grants itself permission to break the rules. Can this be done?

A: No, but there always seem to be holes in any security mechanism. I will say this: It would be extremely difficult to write an applet that steps outside its sandbox without the user granting it permission. It is probably easier for someone to write an applet that tricks a user into agreeing to a signed certificate so that the applet could do anything it wanted on the person’s machine than it is to write Java code that bypasses the built-in security features of applets and the JVM.

Q: So applets really are not that secure, are they?

A: No. Applets by their nature are much safer than other Web applications that do not have a sandbox-type security.If a user has security turned on, an applet cannot leave its sandbox without the express permission of the user. An applet has much tighter security restrictions than HTML, JavaScript, and other widely used Web development technologies.

Sandbox SecuritySandbox Security

Page 75: JAVA GUI

©Silberschatz, Korth and Sudarshan3.75Database System Concepts

Q: Can I turn off the security permissions so my own applets can run on my machine and perform actions such as accessing the local file system?

A: Certainly, how to do this using Microsoft Internet Explorer. You will find that Microsoft has hidden this feature deep in the browser settings, so you will need to work closely.

A: You can if you have an IDE like Visual Café or Visual Age. These IDEs have GUI editors that let you place components exactly where you want them. You can also organize components by assigning a null layout manager to your container and specifying the exact location and size of each component added.

04/08/23 75

Sandbox SecuritySandbox Security

Page 76: JAVA GUI

©Silberschatz, Korth and Sudarshan3.76Database System Concepts

The java.applet.Applet ClassThe java.applet.Applet Class

An applet is a Java class; if the applet is to be viewed in a Web browser, the class must extend the java.applet.Applet class.

The Applet class provides a common interface so that a Web browser can communicate with the applet.

The intersting note about the Applet class is that it extends java.awt.Panel.

Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels.

04/08/23 76

Page 77: JAVA GUI

©Silberschatz, Korth and Sudarshan3.77Database System Concepts

Panel Container for AppletPanel Container for Applet

77

Object

Component

Container

The Class Hierarchy depicts that Panel inherit their common attributescommon attributes and behavior .

Class Panel ( package.java.awt) is subclass of Container and Applet is subclass of Panel

PanelPanel

AppletApplet

Page 78: JAVA GUI

©Silberschatz, Korth and Sudarshan3.78Database System Concepts

Writing AppletWriting Applet

An Applet Class extendsextends Panel means that an applet is a applet is a panelpanel, which is a java.awt.Container;

therefore, an applet can have components added to it just like any container,

as well as have a Layout manager Layout manager assigned to it, and you can even nest panels within an applet to create the GUI you want.

The default layout manager for a panel is the FlowLayout layout manager.

Before taking a look at a simple Applet class named HelloWorldApplet which extends java.applet.Applet, introductory concepts of HTML will be required.

04/08/23 78

Page 79: JAVA GUI

©Silberschatz, Korth and Sudarshan3.79Database System Concepts

Introduction to HTMLIntroduction to HTML HTML stands for HyperText Markup

Language and is the language of the Internet.

A Web page is an HTML document, and HTML looks nothing like the page you actually view.

Your Web browser takes the HTML and marks it up (thus the term “markup” language).

Let us cover a few of the basics so you can create the necessary Web pages to view your applets. HTML consists of tags, which appear in angle brackets <>.

Most tags come in pairs, with an opening and closing tag. For example, the following <strong> tag makes the string “Hello, HTML” appear in bold.

79

<strong> Hello, World </strong>

Notice that a forward slash is used to denote the closing

tag.

Not all tags require a closing tag, however, most tags

come in pairs with an opening and closing tag.

An HTML document is a text file saved with either a .htm

or .html extension.

Page 80: JAVA GUI

©Silberschatz, Korth and Sudarshan3.80Database System Concepts

HTMLHTML

The root tag of an HTML document is <html>, and the <html> tag can nest the optional <head> and <body> tags:

<html>

<head>

</head>

<body>

</body>

</html>

The <head> tag can contain the <title> tag, which denotes the text to appear in the title bar of the browser’s window.

For example, the following Web page displays Welcome in the title bar of the browser and defines keywords that are used by search engines to determine the content of the page:

<header>

<title>Welcome</title>

<meta name=”keywords” content=”java, training, courseware,

books”>

</header>

04/08/23 80

Page 81: JAVA GUI

©Silberschatz, Korth and Sudarshan3.81Database System Concepts

HTML embedding AppletHTML embedding Applet

Three attributes of the <applet> tag that are required:

Code: The name of the applet class for this applet.

Width: The width in pixels of the applet.

Height: The height in pixels of the applet. For example, if the name of your applet class is

com.world.MyApplet, the following HTML embeds an instance of MyApplet in a Web page:

<applet code=”com.world.MyApplet” width=”400” height=”500”>

</applet>

The size of the applet will be 400 pixels wide and 500 pixels high.

04/08/23 81

Page 82: JAVA GUI

©Silberschatz, Korth and Sudarshan3.82Database System Concepts

HelloWorldApplet ClassHelloWorldApplet Class

Few comments about this applet:

This Class is Container Container & adds a button .

There is no main() & Most of the code of the HelloWorldApplet class appears in the init() method, which is overriding the init() method from the parent class Applet.

The Web browser invokes init() immediately after it creates an instance of HelloWorldApplet Class.

We could have used a constructor, but we wanted to demonstrate the init() method.

Within init(), the layout of the applet is changed to BorderLayout. (It had FlowLayout by default.)

The event handling is done in the ensuing PrintHello class. Study the following code, and try to determine what this applet does.

A PrintHello object is listening for an ActionEvent from the Go button.

82

Page 83: JAVA GUI

©Silberschatz, Korth and Sudarshan3.83Database System Concepts

import java.applet.*;

import java.awt.*;

public class HelloWorldApplet extends Applet

{

private Button go;

private TextField name;

private Label hello;

public void init()

{

go = new Button(“Go”);

name = new TextField();

hello = new Label(“”, Label.CENTER);

this.setLayout(new BorderLayout());

this.add(name, BorderLayout.NORTH);

Panel center = new Panel();

center.add(go);

this.add(center, BorderLayout.CENTER);

this.add(hello, BorderLayout.SOUTH);

//Set up the event handling.

PrintHello listener = new PrintHello(hello, name);

go.addActionListener(listener);

}

}

83

import java.awt.*;import java.awt.event.*;public class PrintHello implements ActionListener{private Label label;private TextField textField;public PrintHello(Label s, TextField t){label = s;textField = t;}public void actionPerformed(ActionEvent a){String name = textField.getText();if(name != null && !(name.equals(“”))){label.setText(“Hello, “ + name);}}}

Page 84: JAVA GUI

©Silberschatz, Korth and Sudarshan3.84Database System Concepts

AppletApplet

When a user views an HTML page that contains an applet, the code for the applet code for the applet is downloaded to the user’s machine.

A user must have a JVM on his or her machine. The JVM can be either a plug-in of the Web browser or a separate runtime environment.

The JVM on the user’s machine creates an instance of the applet class and invokes various methods during the applet’s lifetime.

04/08/23 84

Page 85: JAVA GUI

©Silberschatz, Korth and Sudarshan3.85Database System Concepts

Applet Applet

This applet is displayed in a Web page named hello.html using the <applet> tag.

The HTML looks similar to:

<html>

<body>

<h2>Enter your name and click the button.</h2>

<applet code=”HelloWorldAppletHelloWorldApplet”

width=”200”

height=”75”>

</applet>

</body>

</html>

04/08/23 85

Page 86: JAVA GUI

©Silberschatz, Korth and Sudarshan3.86Database System Concepts

04/08/23 86

Sample view of HelloWorldApplet in hello.html file

Sample

Page 87: JAVA GUI

©Silberschatz, Korth and Sudarshan3.87Database System Concepts

Applet embeddingApplet embedding

An applet can actually be embedded within any other application, not just a Web browser.

If your applet is going to be embedded in a Web page, it must extend the Applet class. If your applet is going to be embedded in some other application, extending Applet is not required.

On the same line, we may develop Swing Applets using JApplet.

JApplet class is subclass of Applet so it inherites all the methods of Applet.

The purpose of the JApplet class is to provide support for Swing.

Probably the biggest difference between an applet and a JApplet is how components are added to them.

A JApplet has three panes, much like a JFrame, and components are added to the content pane of the Japplet.

87

Page 88: JAVA GUI

©Silberschatz, Korth and Sudarshan3.88Database System Concepts

Life Cycle methods of an AppletLife Cycle methods of an Applet

Let us discuss the five applet methods that are called by the applet container from the time the applet is loaded into the browser to the time that it is terminated by the browser.

These methods correspond to various aspects of an applet’s life cycle.

These methods are inherited from class Japplet. that the browser invokes these methods on your applet.

1) public void init().

2) public void start().

3) public void stop().

4) public void destroy().

5) public void paint(Graphics g).

04/08/23 88

Page 89: JAVA GUI

©Silberschatz, Korth and Sudarshan3.89Database System Concepts

1)1) public void init(). public void init(). The first method invoked on the applet when it is initially instantiated. This is your chance to perform any initialization, such as locating resources or preparing event handlers.

2)2) public void start(). public void start(). Invoked by the browser to inform the applet that it should start executing. The start() method is called right after the init() method, and is also called when the page is revisited. This is a good time to start any threads or other tasks like displaying animation or playing sound.

3)3) public void stop(). public void stop(). Invoked by the Web browser to inform the applet that it should stop executing. The stop() method is called right before the destroy() method is invoked, and also when a user leaves the Web page.Typically, anything you started in the start() method is stopped in the stop() method.

4)4) public void destroy(). public void destroy(). Invoked by the Web browser to inform the applet that it is about to be destroyed (in other words, garbage collected). Typically,any resources allocated in the init() method are freed in the destroy() method.

5)5) public void paint(Graphics g). public void paint(Graphics g). Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the

89

Page 90: JAVA GUI

©Silberschatz, Korth and Sudarshan3.90Database System Concepts

When a user views a Web page that contains an applet, the following sequence of events occurs regarding the life cycle of the applet:

1. The Web browser downloads the necessary bytecode and JAR file from the Web server where the code is located. (This Web server is referred to as the code base.)

2. The browser creates an instance of the Applet class, invoking the default constructor.

3. The applet is displayed in the Web page, with the location and size of the applet determined by the HTML.

4. The browser invokes the init() method on the applet.

5. The browser invokes the start() method on the applet.

6. The browser invokes the paint() method on the applet.

7. The applet is now live and running within the Web page.

8. The browser calls paint() whenever the applet needs to repaint itself.

9. The browser invokes the stop() method when the user leaves the Web page or the applet is about to be destroyed.

10. The browser invokes the destroy() method just before destroying the applet.

90

Page 91: JAVA GUI

©Silberschatz, Korth and Sudarshan3.91Database System Concepts

Applet & HTMLApplet & HTML

If a Web browser does not understand the <applet> tag, it will ignore the tag and display any HTML that appears within the opening and closing <applet> tags.

For example, the following HTML displays a message that the user is unable to see the applet that was intended to appear:

<applet code=”com.world.MyApplet”

width=”200”

height=”348”

alt=”MyApplet failedMyApplet failed”>

<h2>Your browser does not support applets!</h2>

<p>To view this page correctly, you will need to find a Web

browser that provides support for applets, or install the

Java Plug-in.</p>

</applet>

04/08/23 91

Page 92: JAVA GUI

©Silberschatz, Korth and Sudarshan3.92Database System Concepts

Applet & HTMLApplet & HTML

Visitors to this page who have a Web browser that supports applets will not see the message about their browser not supporting applets. Note that if their browser supports applets but, for some reason, cannot run applets, the visitor will see the alt message “MyApplet failed.”

04/08/23 92

Page 93: JAVA GUI

©Silberschatz, Korth and Sudarshan3.93Database System Concepts

04/08/23 93

Page 94: JAVA GUI

©Silberschatz, Korth and Sudarshan3.94Database System Concepts

04/08/23 94

Page 95: JAVA GUI

©Silberschatz, Korth and Sudarshan3.95Database System Concepts

Playing AudioPlaying Audio

Java has the feature of the playing the sound file.

Let us see how to play a audio clip in your java applet viewer or on the browser.

An applet can play an audio file represented by the AudioClip interface in the java.applet packagejava.applet package.

The AudioClip interface has three methods, including:

public void play()- Plays the audio clip one time, from the beginning.

public void loop()- Causes the audio clip to replay continually.

public void stop()- Stops playing the audio clip.

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class:

public AudioClip getAudioClip(URL url)

95

Page 96: JAVA GUI

©Silberschatz, Korth and Sudarshan3.96Database System Concepts

Audio using AppletAudio using Applet

The getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file.

The audio file is not downloaded until an attempt is made to play the audio clip.

The following AudioDemo applet demonstrates playing an audio clip that is specified as an applet parameter. Study the class, and try to determine how it looks and what it does.

04/08/23 96

Page 97: JAVA GUI

©Silberschatz, Korth and Sudarshan3.97Database System Concepts

import java.applet.*;

import java.awt.*;

import java.net.*;

public class AudioDemo extends Applet

{

private AudioClip clip;

private AppletContext context;

public void init()

{

context = this.getAppletContext();

String audioURL = this.getParameter(“audio”);

if(audioURL == null)

{

audioURL = “default.au”;

}

try

{

URL url = new URL(this.getDocumentBase(), audioURL);

clip = context.getAudioClip(url);

}

04/08/23 97

catch(MalformedURLException e){

e.printStackTrace();context.showStatus(“Could not load

audio file!”);}}

public void start(){

if(clip != null){

clip.loop();}}

public void stop(){

if(clip != null){

clip.stop();}}}

Page 98: JAVA GUI

©Silberschatz, Korth and Sudarshan3.98Database System Concepts

Applet CommunicationApplet Communication

How two applets on the same Web page can communicate with each other using the applet context.

You will have write two applets: one that plays an audio clip, and a second applet that controls which audio clip is played.

04/08/23 98

Page 99: JAVA GUI

©Silberschatz, Korth and Sudarshan3.99Database System Concepts

04/08/23 99

Page 100: JAVA GUI

©Silberschatz, Korth and Sudarshan3.100Database System Concepts

04/08/23 100

Page 101: JAVA GUI

©Silberschatz, Korth and Sudarshan3.101Database System Concepts

04/08/23 101