vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · web view · 2017-04-10unit-v....

79
UNIT-V GUI Programming with java Java AWT (Abstract Window Toolkit) is an API to develop GUI or window- based applications in java. Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS. The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. Java AWT Hierarchy: The hierarchies of Java AWT classes are given below Container The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extend Container class are known as container such as Frame, Dialog and Panel.

Upload: vokhue

Post on 24-Apr-2018

237 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

UNIT-VGUI Programming with java

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

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

Java AWT Hierarchy:

The hierarchies of Java AWT classes are given below

Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extend Container class are known as container such as Frame, Dialog and Panel.

Window

The window is the container that has no borders and menu bars. You must use frame, dialog or another window for creating a window.

Page 2: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.

Useful Methods of Component class:

Page 3: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Java Swings

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing:

There are many differences between java awt and swing that are given below.

Page 4: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Page 5: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Java Swing Examples:

There are two ways to create a frame:

o By creating the object of Frame class (association)

o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example:

Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java

import javax.swing.*; public class FirstSwingExample { public static void main(String[] args) { JFrame f=new JFrame();//creating instance of JFrame

Page 6: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

JButton b=new JButton("click");//creating instance of JButton b.setBounds(130,100,100, 40);//x axis, y axis, width, height f.add(b);//adding button in JFrame f.setSize(400,500);//400 width and 500 height f.setLayout(null);//using no layout managers f.setVisible(true);//making the frame visible } }

Page 7: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Swing Containment Hierarchy:

All Swing GUI applications and applets make use of a containment hierarchy that is more or less unrelated to (or at least different from) the Swing components' position on the class hierarchy.

The containment hierarchy, from top to bottom, is as follows:

1. Top-level Container(s)To appear onscreen, every GUI component must be part of a containment hierarchy. There is at least one containment hierarchy in every program that uses Swing components. Each containment hierarchy has a top-level container at its root. 

2. Intermediate Container(s)Generally speaking, an intermediate container consists of a content pane, or panel, that contains all the visible (atomic) components. Each top-level container must contain at least one intermediate container if there is to be anything useful displayed on the screen. 

3. Atomic Component(s)The button and label are atomic components - self-sufficient entities that present bits of information to the user. Often, atomic components also get input from the user.

Tip:  To view the containment hierarchy for any frame or dialog, click its border to select it, and then press Control-Shift-F1. A list of the containment hierarchy will be written to the standard output stream.

Top-level Containers:

Top-level Containers exist mainly to provide a place for other Swing components to paint themselves. Swing provides four top-level container classes:

JApplet - Enables applets to use Swing components. 

JDialog - The main class for creating a dialog window. 

JFrame - A top-level window with a title and a border. 

JWindow - As a rule, not very useful. Provides a window with no controls or title.

Top-level Containers in Applets

A Swing-based applet has at least one containment hierarchy, exactly one of which is rooted by a JApplet object. For example, an applet that brings up a dialog has two containment hierarchies. The components in the browser window are in a containment hierarchy rooted by a JApplet object. The dialog has a containment hierarchy rooted by a JDialog object.

Page 8: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Top-level Containers in Applications

As a rule, a standalone application with a Swing-based GUI has at least one containment hierarchy with a JFrame as its root. For example, if an application has one main window and two dialogs, then the application has three containment hierarchies, and thus three top-level containers. One containment hierarchy has a JFrame as its root, and each of the other two has a JDialog object as its root.

Intermediate Containers

A panel, or pane, such as JPanel, is an intermediate container. Its only purpose is to simplify the positioning atomic components like buttons and labels. Other intermediate Swing containers, such as scroll panes (JScrollPane) and tabbed panes (JTabbedPane), typically play a more visible, interactive role in a program's GUI.

General-Purpose Intermediate Containers:

Special-Purpose Intermediate Containers:

Atomic Components

Atomic components are self-sufficient entities that present bits of information to the user. The Swing API provides many atomic components, including a button ( JButton), a label (JLabel), combo boxes (JComboBox), text fields (JTextField), and tables (JTable).

Page 9: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Atomic Components - Basic Controls

Atomic Components - Uneditable Information Displays

Atomic Components - Editable Displays of Formatted Information

Page 10: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Swing components and container objectsIn Java, a component is the basic user interface object and is found in all Java applications. Components include lists, buttons, panels, and windows. To use components, you need to place them in a container.

A container is a component that holds and manages other components. Containers display components using a layout manager.

Swing components inherit from the javax.Swing.JComponent class, which is the root of the Swing component hierarchy. JComponent, in turn, inherits from the Container class in the Abstract Windowing Toolkit (AWT). So Swing is based on classes inherited from AWT.Swing provides the following useful top-level containers, all of which inherit from JComponent:

JWindowJWindow is a top-level window that doesn't have any trimmings and can be displayed anywhere on a desktop. JWindow is a heavyweight component. You usually use JWindow to create pop-up windows and "splash" screens. JWindow extends AWT's Window class.

JFrameJFrame is a top-level window that can contain borders and menu bars. JFrame is a subclass of JWindow and is thus a heavyweight component. You place a JFrame on a JWindow. JFrame extends AWT's Frame class.

JDialogJDialog is a lightweight component that you use to create dialog windows. You can place dialog windows on a JFrame or JApplet. JDialog extends AWT's Dialog class.

JAppletJApplet is a container that provides the basis for applets that run within web browsers. JApplet is a lightweight component that can contain other graphical user interface (GUI) components. JApplet extends AWT's Applet class.

All Swing components - including the JApplet and JDialog containers - need to be contained at some level inside a JWindow or JFrame.

Page 11: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Each top-level container depends on another intermediate container called the root, which provides a number of components to each.

JApplet is the root container for Swing applets and JFrame is the root container for a standalone GUI application.

Once you've created a root container, you can add components and other containers to it.

Each top-level container consists of the following panes:

Page 12: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Root paneThe root pane is an intermediate container that manages the layered pane, content pane, and glass pane. It can also manage an optional menu bar. You use a root pane to paint over multiple components or to catch input events. 

Layered paneThe layered pane contains the content pane and the optional menu bar. It can also contain other components, which it arranges so that they overlap each other. This enables you to add pop-up menus to applications. The layered pane provides six functional layers in which you place the components you add to it. You use each of these functional layers for a specific function. 

Content paneThe content pane holds all the visible components of the root pane, except the menu bar. It covers the visible section of the JFrame or JWindow and you use it to add components to the display area. Java automatically creates a content pane when you create a JFrame or JWindow but you can create your own content pane, which has to be opaque. 

Glass paneThe glass pane is invisible by default but you can make it visible. When it is visible, it covers the components of the content pane, blocks all input events from reading these components, and can paint over an existing area containing one or more components.

One of the enhancements to JTabbedPane is the use of a component to represent the tab in a JTabbedPane. This new feature offers a convenient way to show several items in a small amount of space. It does this by dividing the information across separate tabs so that a user can select

one tab to list a particular set of components a different tab to list a different set of components

By adding a Close button, you can enable the removal of the current tab from JTabbedPane.

Page 13: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

JComponent services:

JComponent is the root class for all Swing components such as JPanel, JLabel, and JButton. This class inherits from the Container class and enables you to add containers and components to an application.

The JComponent class provides the following functionality features to its subclasses:

Customizing component appearance Checking component states Adding event handling Painting components Modifying the containment hierarchy Arranging the layout of components Retrieving component size and position information TextComponent Printing

Customizing component appearanceYou can change the appearance of a component by setting the border, foreground color, background color, font, and a cursor to display when moving over the component.

The most commonly used methods to change the appearance of a component include the setForeground and setBackground methods, which enable you to set the colors for a component. 

The setForeground method sets the color for a component's text and the setBackground method sets the color for the background areas of a component.You can also set a component to be opaque.

For example, consider the code used to change the background color of a JLabel - called label - to black.

Page 14: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The code to change the background color of a label is:

label.setBackground(Color.black); 

Checking component statesThe JComponent class enables you to determine the state of components. You can add tooltips and specify names for components, using the setToolTipText and setName methods, respectively. You can also use the isEnabled method to check whether a component is enabled to generate events from user input. You can set a component to be visible using the setVisible method. You can also determine whether a component is visible onscreen by using the isShowing method.

 Adding event handlingThe JComponent class provides methods that enable you to add and remove event listeners for mouse clicks, mouse movements, key presses, or component changes.

These methods include addMouseListener, addMouseMotionListener, addKeyListener and  addComponentListener.

JComponent provides a method - setTransferHandler - that you can use to enable the transfer of data using the Drag-and-Drop feature or via cut, copy, or paste functions.

You can check which component contains a specific point using the contains method. You can also determine which component lies at a specified position using the getComponentAt method.

 Painting componentsJComponent provides methods that enable you to customize painting for all its subclasses. You can use the repaint method to repaint a component or a specific part within it.You can refresh the layout of a component and its associated containers using the revalidate method. However, you usually invoke this method if you change the containment hierarchy or the size of a component.

Page 15: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Modifying the containment hierarchyYou can add or remove one or more components to a container using add and remove methods, respectively.When adding or removing a component, you can specify the component's position in the container using the add method with an int argument. If you do not specify a component's position, it is placed at the end of the container.

 Arranging the layout of components

You can add or remove components from a container using a layout manager or absolute position. To specify a layout manager, you can use the setLayout and getLayout methods. You can also specify a preferred, maximum, or minimum size of any Component object, using the setPreferredSize, setMaximumSize, and setMinimumSize methods, respectively. Some layout managers will respect the preferred size, such as FlowLayout. Other Layout managers will ignore the preferred size, such as BorderLayout. So setting the preferredSize may not automatically yield the desired result in component size, because the layout manager will have an effect on the component sizes. Using the layout manager enables you to set the alignment and orientation of a component. When using an absolute position, you can specify a component's location or size. To do this, you can use the setLocation and setSize methods, respectively.You can also set the location and size using just one method, setBounds, which takes four integer parameters.

 Retrieving component size and position informationYou can retrieve information about the current width, height, size, and position of a component. To do this, you can use separate methods - getWidth, getHeight, getSize, and getLocation - or you can use the getBounds method, which retrieves all this information simultaneously.JComponent provides a method - getInsets - that enables you to retrieve information about a component's border size.

 TextComponent PrintingJava SE 6 simplifies the printing of the different JTextComponent elements. JTextField, JTextArea, and JTextPane contents can now be printed without any concern about pagination. This is now performed using any of the three new print methods added to the JTextComponent class. 

Page 16: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Layout management:BorderLayout (LayoutManagers)

LayoutManagers:

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:

1. java.awt.BorderLayout

2. java.awt.FlowLayout

3. java.awt.GridLayout

4. java.awt.CardLayout

5. java.awt.GridBagLayout

6. javax.swing.BoxLayout

7. javax.swing.GroupLayout

8. javax.swing.ScrollPaneLayout

9. javax.swing.SpringLayout etc.

BorderLayout:

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH

2. public static final int SOUTH

3. public static final int EAST

4. public static final int WEST

5. public static final int CENTER

Page 17: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the components.

o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and

vertical gaps between the components.

Example of BorderLayout class:

import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER");; f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST);

Page 18: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } }

GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

Constructors of GridLayout class:

1. GridLayout(): creates a grid layout with one column per component in a row.

2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components.

3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class:

Page 19: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

import java.awt.*; import javax.swing.*; public class MyGridLayout{ JFrame f; MyGridLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyGridLayout(); } }

Page 20: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the

default layout of applet or panel.

Fields of FlowLayout class:

1. public static final int LEFT

2. public static final int RIGHT

3. public static final int CENTER

4. public static final int LEADING

5. public static final int TRAILING

Constructors of FlowLayout class:

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal

and vertical gap.

2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit

horizontal and vertical gap.

3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment

and the given horizontal and vertical gap.

Example of FlowLayout class:

import java.awt.*;

Page 21: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

import javax.swing.*; public class MyFlowLayout{ JFrame f; MyFlowLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.setLayout(new FlowLayout(FlowLayout.RIGHT)); //setting flow layout of right alignment f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyFlowLayout(); } }

Page 22: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of

source. Events are generated as result of user interaction with the graphical user interface

components. For example, clicking on a button, moving the mouse, entering a character through

keyboard,selecting an item from list, scrolling the page are the activities that causes an event to

happen.

Types of Event

The events can be broadly classified into two categories:

Foreground Events - Those events which require the direct interaction of

user.They are generated as consequences of a person interacting with the

graphical components in Graphical User Interface. For example, clicking on a

button, moving the mouse, entering a character through keyboard,selecting an

item from list, scrolling the page etc.

Background Events - Those events that require the interaction of end user are

known as background events. Operating system interrupts, hardware or software

failure, timer expires, an operation completion are the example of background

events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an

event occurs. These mechanisms have the code which is known as event handler that is

executed when an event occurs. Java Uses the Delegation Event Model to handle the events.

This model defines the standard mechanism to generate and handle the events.Let's have a brief

introduction to this model.

Page 23: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The Delegation Event Model has the following key participants namely:

Source - The source is an object on which event occurs. Source is responsible for

providing information of the occurred event to it's handler. Java provide as with

classes for source object.

Listener - It is also known as event handler.Listener is responsible for generating

response to an event. From java implementation point of view the listener is also

an object. Listener waits until it receives an event. Once the event is received , the

listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the

logic that generates the event. The user interface element is able to delegate the processing of an

event to the separate piece of code. In this model ,Listener needs to be registered with the

source object so that the listener can receive the event notification. This is an efficient way of

handling the event because the event notifications are sent only to those listener that want to

receive them.

Steps involved in event handling

The User clicks the button and the event is generated.

Now the object of concerned event class is created automatically and information about

the source and the event get populated with in same object.

Event object is forwarded to the method of registered listener class.

The method is now get executed and returns.

Points to remember about listener

In order to design a listener class we have to develop some listener interfaces.These

Listener interfaces forecast some public abstract callback methods which must be

implemented by the listener class.

If you do not implement the any if the predefined interfaces then your class can not act as

a listener class for a source object.

Page 24: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Callback Methods

These are the methods that are provided by API provider and are defined by the application

programmer and invoked by the application developer. Here the callback methods represents an

event method. In response to an event java jre will fire callback method. All such callback

methods are provided in listener interfaces.

If a component wants some listener will listen to it's events the the source must register itself to

the listener.

Event Handling Example

Create the following java program using any editor of your choice in say D:/ > SWING > com

> tutorialspoint > gui >

SwingControlDemo.javapackage com.tutorialspoint.gui;

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class SwingControlDemo {

private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel;

public SwingControlDemo(){ prepareGUI(); }

public static void main(String[] args){ SwingControlDemo swingControlDemo = new SwingControlDemo(); swingControlDemo.showEventDemo(); } private void prepareGUI(){

Page 25: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1));

headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){

System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); }

private void showEventDemo(){ headerLabel.setText("Control in action: Button");

JButton okButton = new JButton("OK"); JButton submitButton = new JButton("Submit"); JButton cancelButton = new JButton("Cancel");

okButton.setActionCommand("OK"); submitButton.setActionCommand("Submit"); cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener()); submitButton.addActionListener(new ButtonClickListener()); cancelButton.addActionListener(new ButtonClickListener());

controlPanel.add(okButton); controlPanel.add(submitButton); controlPanel.add(cancelButton);

Page 26: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

mainFrame.setVisible(true); }

private class ButtonClickListener implements ActionListener{ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if( command.equals( "OK" )) { statusLabel.setText("Ok Button clicked."); } else if( command.equals( "Submit" ) ) { statusLabel.setText("Submit Button clicked."); } else { statusLabel.setText("Cancel Button clicked."); } } }}Compile the program using command prompt. Go to D:/ > SWING and type the following command.D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.javaIf no error comes that means compilation is successful. Run the program using following command.D:\AWT>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Page 27: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Event Classes

The Event classes represent the event. Java provides us various Event classes but we will

discuss those which are more frequently used.

EventObject class

It is the root class from which all event state objects shall be derived. All Events are constructed

with a reference to the object, the source, that is logically deemed to be the object upon which

the Event in question initially occurred upon. This class is defined in java.util package.

Class declaration

Following is the declaration for java.util.EventObject class:

public class EventObject extends Object implements Serializable

Field

Following are the fields for java.util.EventObject class:

protected Object source -- The object on which the Event initially occurred.

Class constructors1. EventObject(Object source): Constructs a prototypical Event.

Class methods1. Object getSource(): The object on which the Event initially occurred.2. String toString(): Returns a String representation of this EventObject.

Methods inherited

This class inherits methods from the following classes:

java.lang.Object

Page 28: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

SWING Event Classes:

Following is the list of commonly used event classes.

Control & DescriptionAWTEventIt is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class.

ActionEventThe ActionEvent is generated when button is clicked or the item of a list is double clicked.

InputEventThe InputEvent class is root event class for all component-level input events.

KeyEventOn entering the character the Key event is generated.

MouseEventThis event indicates a mouse action occurred in a component.

WindowEventThe object of this class represents the change in state of a window.

AdjustmentEventThe object of this class represents the adjustment event emitted by Adjustable objects.

ComponentEventThe object of this class represents the change in state of a window.

ContainerEventThe object of this class represents the change in state of a window.

MouseMotionEventThe object of this class represents the change in state of a window.

PaintEventThe object of this class represents the change in state of a window.

Page 29: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Event Adapters

Adapters are abstract classes for receiving various events. The methods in these classes are

empty. These classes exist as convenience for creating listener objects.

SWING Adapters:

Following is the list of commonly used adapters while listening GUI events in SWING.

Adapter & Description

FocusAdapter

An abstract adapter class for receiving focus events.

KeyAdapter

An abstract adapter class for receiving key events.

MouseAdapter

An abstract adapter class for receiving mouse events.

MouseMotionAdapter

An abstract adapter class for receiving mouse motion events.

WindowAdapter

An abstract adapter class for receiving window events.

Page 30: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Event Listeners

The Event listener represent the interfaces responsible to handle events. Java provides us

various Event listener classes but we will discuss those which are more frequently used. Every

method of an event listener method has a single argument as an object which is subclass of

EventObject class. For example, mouse event listener methods will accept instance of

MouseEvent, where MouseEvent derives from EventObject.

EventListner interface

It is a marker interface which every listener interface has to extend.This class is defined in

java.util package.

Class declaration

Following is the declaration for java.util.EventListener interface:

public interface EventListenerControl & Description:ActionListenerThis interface is used for receiving the action events.

ComponentListenerThis interface is used for receiving the component events.

ItemListenerThis interface is used for receiving the item events.

KeyListenerThis interface is used for receiving the key events.

MouseListenerThis interface is used for receiving the mouse events.

WindowListenerThis interface is used for receiving the window events.

AdjustmentListenerThis interface is used for receiving the adjusmtent events.

Page 31: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

ContainerListenerThis interface is used for receiving the container events.

MouseMotionListenerThis interface is used for receiving the mouse motion events.

FocusListenerThis interface is used for receiving the focus events.

Page 32: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Java’s delegation event model The event model is based on the Event Source and Event Listeners. Event Listener is an object that receives the messages / events. The Event Source is any object which creates the message / event. The Event Delegation model is based on – The Event Classes, The Event Listeners, Event Objects.

There are three participants in event delegation model in Java;

1. Event Source – the class which broadcasts the events2. Event Listeners – the classes which receive notifications of events3. Event Object – the class object which describes the event.

An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted by the event source by invoking an agreed method on all event listeners. The event object is passed as argument to the agreed-upon method. Later the event listeners respond as they fit, like submit a form, displaying a message / alert etc.

PurposeThis document explains the rationale behind introducing a new event model into the AWT and describes specifically how the new model maps to the AWT API. This new model has also been adopted by the JavaBeans architecture for general event processing and is described at a high level in the JavaBeans Specification document.

The 1.0 Event ModelThe model for event processing in version 1.0 of the AWT is based on inheritance. In order for a program to catch and process GUI events, it must subclass GUI components and override either action() or handleEvent() methods. Returning "true" from one of these methods consumes the event so it is not processed further; otherwise the event is propagated sequentially up the GUI hierarchy until either it is consumed or the root of the hierarchy is reached. The result of this model is that programs have essentially two choices for structuring their event-handling code:

1. Each individual component can be subclassed to specifically handle its target events. The result of this is a plethora of classes.

2. All events for an entire hierarchy (or subset thereof) can be handled by a particular container; the result is that the container's overridden action() or handleEvent() method must contain a complex conditional statement in order to process the events.

Issues with the 1.0 Event ModelWhile the above model works fine for small applets with simple interfaces, it does not scale well for larger java programs for the following reasons:

Page 33: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The requirement to subclass a component in order make any real use of its functionality is cumbersome to developers; subclassing should be reserved for circumstances where components are being extended in some functional or visual way.

The inheritance model does not lend itself well to maintaining a clean separation between the application model and the GUI because application code must be integrated directly into the subclassed components at some level.

Since ALL event types are filtered through the same methods, the logic to process the different event types (and possibly the event targets in approach #2) is complex and error-prone. It is not uncommon for programs to have perplexing bugs that are the result of returning an incorrect result (true or false) from the handleEvent() method. This becomes an even greater problem as new event types are added to the AWT; if the logic of existing handleEvent() methods isn't set up to deal properly with unknown types, programs could potentially break in very unpredictable ways.

There is no filtering of events. Events are always delivered to components regardless of whether the components actually handle them or not. This is a general performance problem, particularly with high-frequency type events such as mouse moves.

For many components, the action() method passes a String parameter which is equivalent to either the label of the component (Button, MenuItem) or the item selected (List, Choice). For programs which use approach #2, this often leads to poor coding and unwieldy string-compare logic that doesn't localize well.

The Delegation ModelThe JDK1.1 will introduce a new delegation-based event model in AWT in order to:

Resolve the problems mentioned previously Provide a more robust framework to support more complex java programs.

Design GoalsThe primary design goals of the new model in the AWT are the following:

Simple and easy to learn Support a clean separation between application and GUI code Facilitate the creation of robust event handling code which is less error-prone (strong

compile-time checking) Flexible enough to enable varied application models for event flow and propagation For visual tool builders, enable run-time discovery of both events that a component

generates as well as the events it may observe Support backward binary compatibility with the old model

Note: These goals are described from the particular perspective of the AWT. Since this model has also been designed to accommodate the JavaBeans architecture, the design goals from the JavaBeans perspective are described in the "Events" section of the JavaBeans Specification and may vary slightly from these goals.

Page 34: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Delegation Model OverviewEvent types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated.

A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. An EventListener interface defines one or more methods which are to be invoked by the event source in response to each specific event type handled by the interface.

An Event Source is an object which originates or "fires" events. The source defines the set of events it emits by providing a set of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for mult-cast) methods which are used to register specific listeners for those events.

In an AWT program, the event source is typically a GUI component and the listener is commonly an "adapter" object which implements the appropriate listener (or set of listeners) in order for an application to control the flow/handling of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.

Event HierarchyEvents are no longer represented by a single Event class (like java.awt.Event) with numeric ids, but instead by a hierarchy of event classes. Each event class is defined by the data representing that event type or related group of events types.

Since a single event class may be used to represent more than one event type (i.e. MouseEvent represents mouse up, mouse down, mouse drag, mouse move, etc), some event classes may also contain an "id" (unique within that class) which maps to its specific event types.

The event classes contain no public fields; the data in the event is completely encapsulated by proper get<Attr>()/set<Attr>() methods (where set<Attr>() only exists for attributes on an event that could be modified by a listener).

Although these are the concrete set defined by the AWT, programs are free to define their own event types by subclassing either java.util.EventObject or one of the AWT event classes. Programs should choose event ID values which are greater than the constant:

java.awt.AWTEvent.RESERVED_ID_MAX

Page 35: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Low-level vs. Semantic EventsThe AWT provides two conceptual types of events: low-level and semantic.

A low-level event is one which represents a low-level input or window-system occurrence on a visual component on the screen. The low-level event classes defined by the AWT are as follows:

java.util.EventObjectjava.awt.AWTEvent java.awt.event.ComponentEvent (component resized, moved, etc.)

java.awt.event.FocusEvent (component got focus, lost focus)java.awt.event.InputEvent java.awt.event.KeyEvent (component got key-press, key-release,

etc.) java.awt.event.MouseEvent (component got mouse-down, mouse-

move, etc.)java.awt.event.ContainerEventjava.awt.event.WindowEvent

Semantic events are defined at a higher-level to encapsulate the semantics of a user interface component's model. The semantic event classes defined by the AWT are as follows:

java.util.EventObject java.awt.AWTEvent

java.awt.event.ActionEvent ("do a command")java.awt.event.AdjustmentEvent ("value was adjusted")java.awt.event.ItemEvent ("item state has changed")java.awt.event.TextEvent ("the value of the text object changed")

Note that these semantic events are not tied to specific screen-based component classes, but may apply across a set of components which implement a similar semantic model. For example, a Button object will fire an "action" event when it is pressed, a List object will fire an "action" event when an item is double-clicked, a MenuItem will fire an "action" event when it was selected from a menu, and a non-visual Timer object might fire an "action" when its timer goes off (the latter is a hypothetical case).

Event ListenersAn EventListener interface will typically have a separate method for each distinct event type the event class represents. So in essence, particular event semantics are defined by the combination of an Event class paired with a particular method in an EventListener. For example, the FocusEventListener interface defines two methods, focusGained() and focusLost(), one for each event type that FocusEvent class represents.

The API attempts to define a balance between providing a reasonable granularity of Listener interface types and not providing a separate interface for every single event type.

The low-level listener interfaces defined by the AWT are as follows:

Page 36: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

java.util.EventListener java.awt.event.ComponentListener java.awt.event.ContainerListener java.awt.event.FocusListener java.awt.event.KeyListener java.awt.event.MouseListener java.awt.event.MouseMotionListener java.awt.event.WindowListener

The semantic listener interfaces defined by the AWT are as follows:

java.util.EventListener java.awt.event.ActionListener java.awt.event.AdjustmentListener java.awt.event.ItemListener java.awt.event.TextListener

Event SourcesBecause the events fired by an event source are defined by particular methods on that object, it is completely clear from the API documentation (as well as by using run-time introspection techniques) exactly which events an object supports.

All AWT event sources support a multicast model for listeners. This means that multiple listeners can be added and removed from a single source. The API makes no guarantees about the order in which the events are delivered to a set of registered listeners for a given event on a given source. Additionally, any event which allows its properties to be modified (via setXXX() methods) will be explicitly copied such that each listener receives a replica of the original event. If the order in which events are delivered to listeners is a factor for your program, you should chain the listeners off a single listener which is registered on the source (the fact that the event data is encapsulated in a single object makes propagating the event extremely simple).

Event delivery is synchronous (as with 1.0's handleEvent()), however programs should not make the assumption that the delivery of an event to a set of listeners will occur on the same thread.

Once again, a distinction is drawn between low-level and semantic events. For low-level events, the source will be one of the visual component classes (Button, Scrollbar, etc) since the event is tightly bound to the actual component on the screen. The low-level listeners are defined on the following components:

java.awt.Component

addComponentListener(ComponentListener l)addFocusListener(FocusListener l)addKeyListener(KeyListener l)addMouseListener(MouseListener l)addMouseMotionListener(MouseMotionListener l)

Page 37: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

java.awt.Container

addContainerListener(ContainerListener l)

java.awt.Dialog

addWindowListener(WindowListener l)

java.awt.Frame

addWindowListener(WindowListener l)

For semantic events, the source is typically a higher-level interface representing the semantic model (and this higher-level interface is commonly `implemented' by components using the model). Following are the semantic listeners defined for AWT components:

java.awt.Button

addActionListener(ActionListener l)

java.awt.Choice (implements java.awt.ItemSelectable)

addItemListener(ItemListener l)

java.awt.Checkbox (implements java.awt.ItemSelectable)

addItemListener(ItemListener l)

java.awt.CheckboxMenuItem (implements java.awt.ItemSelectable)

addItemListener(ItemListener l)

java.awt.List (implements java.awt.ItemSelectable)

addActionListener(ActionListener l)addItemListener(ItemListener l)

java.awt.MenuItem

addActionListener(ActionListener l)

java.awt.Scrollbar (implements java.awt.Adjustable)

addAdjustmentListener(AdjustmentListener l)

java.awt.TextArea

Page 38: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

addTextListener(TextListener l)

java.awt.TextField

addActionListener(ActionListener l)addTextListener(TextListener l)

AdaptersSince many of the EventListener interfaces are designed to listen to multiple event subtypes (i.e. the MouseListener listens to mouse-down, mouse-up, mouse-enter, etc.), the AWT will provide a a set of abstract "adapter" classes, one which implements each listener interface. This will allow programs to easily subclass the Adapters and override ONLY the methods representing event types they are interested in.

The Adapter classes provided by AWT are as follows:

java.awt.event.ComponentAdapterjava.awt.event.ContainerAdapterjava.awt.event.FocusAdapterjava.awt.event.KeyAdapterjava.awt.event.MouseAdapterjava.awt.event.MouseMotionAdapterjava.awt.event.WindowAdapter

Note: There are no default Adapters provided for the semantic listeners, since each of those only contain a single method and an adapter would provide no real value.

Filtering for PerformanceOne of the great benefits of the new model is that since listeners are registered to handle specific event types, it's relatively easy for the toolkit to filter the events and deliver ONLY the events a component is interested in. This was not true with the old model!. Filtering should improve performance, especially with high frequency type events, such as mouse-moves.

All platforms should see some performance improvement from reduced event traffic, but the Solaris implementation should gain exceptional improvement since it's a network-based window system.

Page 39: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Code ExampleFollowing is some sample code that uses the new model:

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

public class App { public void search() { /* do search operation ...*/ System.out.println("Searching..."); } public void sort() { /* do sort operation ...*/ System.out.println("Sorting...."); }

static public void main(String args[]) { App app = new App(); GUI gui = new GUI(app); }}

class Command implements ActionListener { static final int SEARCH = 0; static final int SORT = 1; int id; App app;

public Command(int id, App app) { this.id = id; this.app = app; }

public void actionPerformed(ActionEvent e) { switch(id) { case SEARCH: app.search(); break; case SORT: app.sort(); break; } }}

class GUI {

Page 40: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

public GUI(App app) { Frame f = new Frame(); f.setLayout(new FlowLayout());

Command searchCmd = new Command(Command.SEARCH, app); Command sortCmd = new Command(Command.SORT, app);

Button b; f.add(b = new Button("Search")); b.addActionListener(searchCmd); f.add(b = new Button("Sort")); b.addActionListener(sortCmd);

List l; f.add(l = new List()); l.add("Alphabetical"); l.add("Chronological"); l.addActionListener(sortCmd); f.pack();

f.show(); }}

Note in particular the following differences between this example and how this would have been implemented in the old model:

The application code/logic is completely separate from the GUI. The GUI can be modified (or alternatives provided) without touching the application-specific code. This benefit may not be as apparent from this over-simplified case. However, as applications get larger and more complex, this becomes extremely important.

Absolutely no subclassing of AWT components is required. ONLY the action events are delivered to this program; in the old model all other events

would have also been delivered even though they performed no required function. This code is not necessarily leaner than the code that would have been required for the

old event model. This is mostly due to the requirement for writing the adapter class which listens to the events and dispatches them into application commands appropriately. The adapter classes are required because the Java language supports neither method references nor closures. In this context, it was believed that using interfaces/adapters would be the most type-safe option for making connections between objects. This code could be condensed by using the new JDK1.1 "Inner classes" java language feature.

Page 41: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Handling Events in Extended ComponentsFor Java programs which are extending component classes via subclassing, it would be burdensome to require the registration of separate listener objects to respond to events. Therefore, for this case, the AWT defines that each component provide specific protected methods (that can be overridden by subclasses) which actually dispatch the events to listeners if they exist. This way a subclass can simply override one of these methods in order to process an event.

In order to make this as flexible as possible, this event processing capability is provided in two levels. The first is a single method on all components:

protected void processEvent(AWTEvent)All events for a component are first funneled through this method so that subclasses can choose to handle all events in a single place (similar to the 1.0 model's "handleEvent" with the main difference being that events are NOT propagated up the containment hierarchy in the new model).

The second option for processing events is provided at the event class level; there is a separate method for each class of event handled by that component:

protected void processEventClass(EventClass)For example, the java.awt.List component has the following event-class processing methods:

protected void processActionEvent(ActionEvent e)

protected void processItemEvent(ItemEvent e)By default, the single processEvent method will invoke the proper event-class processing method. The event-class processing method by default will invoke any listeners which are registered. It's important to remember that these methods perform a critical function in the event processing for an AWT component and so if you override them you should remember to call the superclass's method somewhere within your own!

Selecting for Event Types:One of the goals of the listener model is to improve performance by NOT delivering events which components are not interested in. By default, if a listener type is not registered on a component, then those events will NOT be delivered and these processing methods will therefore NOT be called. So if you are using this extension mechanism for event-handling, you'll need to select for the specific types of events your component wishes to receive (in case no listener is registered). This can be done by using the following method on java.awt.Component:

protected final void enableEvents(long eventsToEnable)The parameter to this method is a bitwise mask of the event types you wish to enable. The event masks are defined in java.awt.AWTEvent. Note that changing this mask will not affect the

Page 42: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

delivery of events to listeners -- it only controls the delivery to the component's processing methods. The bottom line is that the set of events which are delivered to processEvent() is defined by the union of event types which have listeners registered and event types explicitly turned on via enableEvents().

Example using Extension MechanismFollowing is an example of how this extension mechanism may be used. For Example, if a subclass of java.awt.Canvas wishes to render some visual feedback when it receives/loses keyboard focus, it could do the following.

public class TextCanvas extends Canvas {

boolean haveFocus = false;

public TextCanvas() { enableEvents(AWTEvent.FOCUS_EVENT_MASK); // ensure we get focus

events ... } protected void processFocusEvent(FocusEvent e) { switch(e.getID()) { case FocusEvent.FOCUS_GAINED: haveFocus = true; break; case FocusEvent.FOCUS_LOST: haveFocus = false; } repaint(); // need to repaint with focus feedback on or off...

super.processFocusEvent(e); // let superclass dispatch to listeners } public void paint(Graphics g) { if (haveFocus) { // render focus feedback... } } ...rest of TextCanvas class...

}

A Word of CautionIn general we recommend you use the delegation-based listener model for most of your basic event handling needs and reserve the use of the above when you are truly extending the look or behavior of a component. This is because the above mechanism suffers from some of the same ills as the 1.0 event model (complex, error-prone logic in processing methods, forgetting to call "super.processEvent", etc.), and unless you clearly understand what you are doing, your program may not behave as you expect!

Page 43: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

An alternative to using the above approach would be to simply have your component subclass implement the particular listener interface for the events it wishes to receive and then register itself as a listener. For example, the above code example would be rewritten to:

public class TextCanvas extends Canvas implements FocusListener {

boolean haveFocus = false;

public TextCanvas() { addFocusListener(this); // ensure we get focus events } public void focusGained(FocusEvent e) { haveFocus = true; repaint();

} public void focusLost(FocusEvent e) { haveFocus = false; repaint(); } public void paint(Graphics g) { if (haveFocus) { // render focus feedback... } } ...rest of TextCanvas class...

}

Consuming EventsThere are cases where programs need to prevent certain types of events from being processed normally by a component (i.e. a builder wants to use mouse events to enable a user to graphically move a button around and it wants to prevent the mouse press from 'pushing' the button).

We have explicitly enabled this capability for input events only by providing two methods on java.awt.event.InputEvent:

public void consume()

public boolean isConsumed()

Note that if some object 'consumes' an input event, it is strictly an indication to the source component that the event should not be processed in its default manner (i.e. consuming a mousePressed event on a Button will prevent it from being activated). The event will still be dispatched to all listeners registered, regardless of whether a listener in the chain consumes the event.

Page 44: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The Event QueueAnother feature of the 1.1 event model is the addition of an event queue class:

java.awt.EventQueueThis class provides a number of public instance methods to manipulate the queue:

public synchronized void postEvent(AWTEvent e)

public synchronized AWTEvent getNextEvent()

public synchronized AWTEvent peekEvent()

public synchronized AWTEvent peekEvent(int eventID)Programs can actually use this class to instantiate their own event queue instances for the purpose of asynchronously posting events. The EventQueue class automatically instantiates an internal thread for dispatching the events appropriately.

In the default JDK implementation, all events generated on components are first posted to a special "system" EventQueue instance before being dispatched to their target component.

The Toolkit class provides a method to access the handle of the system EventQueue instance:

public final EventQueue getSystemEventQueue()

It would obviously be a security problem to allow untrusted applets to freely manipulate the system event queue, therefore the getSystemEventQueue() method is protected by a SecurityManager check which disallows applets direct access to the system queue. We realize that applets would also like access to an event queue which is scoped to their own containment hierarchies and we are working on an architecture to allow that for a follow-on release.

Compatibility with the old ModelOur intention is to maintain binary compatibility for programs written to the old model for the 1.1 release. However, we strongly recommend new java programs migrate to the new model. We do not encourage the explicit mixing of the two models within a single Applet. However, we realize that programs which code to the new model may need/wish to use existing GUI classes which still use the old model and so we have done our best to ensure this works (for example, the hotjava browser is a java application which will need to be able to load both 1.0 and 1.1 style applets).

Page 45: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The way this works is that the AWT will recognize a component as being either a 1.0-event-model "target" OR a 1.1-event-model "source", but not both. A component is recognized to be a 1.1-event-model "source" by meeting one of the following conditions:

1. A listener (of any kind) is registered 2. An event type (of any kind) was explicitly enabled by calling enableEvents()

ELSE the component will be treated as a 1.0-event-model "target" and all events will be delivered to the 1.0 handleEvent method as before.

Note that this is an "all or nothing" distinction and that once the AWT determines a component is a particular event model type, ALL events on that component will be processed in that context. For example, if a TextField object has only a FocusListener registered, then only focus events will be dispatched to the textfield in the 1.1 mechanism and the old 1.0 handleEvent method will NEVER be called (not even for other event types!). So while it is possible to combine components which use the different models, it is not possible to get a single component to mix both models.

One key difference between the two models is that the old model would automatically propagate events up the containment hierarchy, while the new model does NOT propagate events in this way. The way this works for compatibility is that if an event originates on a component which is a 1.0-event-model "target", then it WILL be propagated up the hierarchy in the 1.0 fashion, regardless of the event model type of its ancestor containers. If an event originates on a 1.1-event-model "source", then that event will NOT propagate up the hierarchy, regardless of the event model type of its ancestor containers.

Page 46: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Applet Basics

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.

There are some important differences between an applet and a 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 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 JVM is required to view an applet. 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. 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.

Hierarchy of Applet

Page 47: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

As shown in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component.

Life Cycle of an Applet

Four methods in the Applet class gives you the framework on which you build any serious applet

init − This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.

start − This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.

stop − This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.

destroy − This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.

paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java −

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

public class HelloWorldApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello World", 25, 50); }}

These import statements bring the classes into the scope of our applet class −

java.applet.Applet java.awt.Graphics

Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to.

Page 48: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The Applet Class

Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context.

These include methods that do the following −

Get applet parameters Get the network location of the HTML file that contains the applet Get the network location of the applet class directory Print a status message in the browser Fetch an image Fetch an audio clip Play an audio clip Resize the applet

Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet's execution. The viewer may −

Request information about the author, version, and copyright of the applet Request a description of the parameters the applet recognizes Initialize the applet Destroy the applet Start the applet's execution Stop the applet's execution

The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet

An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes the "Hello, World" applet −

<html> <title>The Hello, World Applet</title> <hr> <applet code = "HelloWorldApplet.class" width = "320" height = "120">

Page 49: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

If your browser was Java-enabled, a "Hello, World" message would appear here. </applet> <hr></html>

Note − You can refer to HTML Applet Tag to understand more about calling applet from HTML.

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with an </applet> tag.

If an applet takes parameters, values may be passed for the parameters by adding <param> tags between <applet> and </applet>. The browser ignores text and other tags between the applet tags.

Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.

The viewer or browser looks for the compiled Java code at the location of the document. To specify otherwise, use the codebase attribute of the <applet> tag as shown −

<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class" width = "320" height = "120">If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period character (.) to separate package/class components. For example<applet = "mypackage.subpackage.TestApplet.class" width = "320" height = "120">

Getting Applet Parameters

The following example demonstrates how to make an applet respond to setup parameters specified in the document. This applet displays a checkerboard pattern of black and a second color.

The second color and the size of each square may be specified as parameters to the applet within the document.

CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint() method. However, getting the values and saving the settings once at the start of the applet, instead of at every refresh, is convenient and efficient.

Page 50: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once, immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override the default implementation to insert custom initialization code.

The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a parameter is always a string). If the value is numeric or other non-character data, the string must be parsed.

The following is a skeleton of CheckerApplet.java

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

public class CheckerApplet extends Applet { int squareSize = 50; // initialized to default size public void init() {} private void parseSquareSize (String param) {} private Color parseColor (String param) {} public void paint (Graphics g) {}}Here are CheckerApplet's init() and private parseSquareSize() methodspublic void init () { String squareSizeParam = getParameter ("squareSize"); parseSquareSize (squareSizeParam); String colorParam = getParameter ("color"); Color fg = parseColor (colorParam); setBackground (Color.black); setForeground (fg);}

private void parseSquareSize (String param) { if (param == null) return; try { squareSize = Integer.parseInt (param); }catch (Exception e) { // Let default value remain }}

Page 51: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt() throws an exception whenever its argument is invalid.

Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.

The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a series of string comparisons to match the parameter value to the name of a predefined color. You need to implement these methods to make this applet work.

Specifying Applet Parameters

The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file specifies both parameters to the applet by means of the <param> tag.

<html> <title>Checkerboard Applet</title> <hr> <applet code = "CheckerApplet.class" width = "480" height = "320"> <param name = "color" value = "blue"> <param name = "squaresize" value = "30"> </applet> <hr></html>

Note − Parameter names are not case sensitive.

Application Conversion to Applets

It is easy to convert a graphical Java application (that is, an application that uses the AWT and that you can start with the Java program launcher) into an applet that you can embed in a web page.

Following are the specific steps for converting an application to an applet.

Make an HTML page with the appropriate tag to load the applet code. Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet

cannot be loaded. Eliminate the main method in the application. Do not construct a frame window for the

application. Your application will be displayed inside the browser. Move any initialization code from the frame window constructor to the init method of the

applet. You don't need to explicitly construct the applet object. The browser instantiates it for you and calls the init method.

Page 52: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.

Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.

If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You can, of course, title the web page itself, using the HTML title tag.)

Don't call setVisible(true). The applet is displayed automatically.

Java Applet Security

A Java applet downloaded from the Web runs in either a Java-enabled Web browser or a Java appletviewer, which is provided in the J2SE bundle. From a security standpoint, Java applets downloaded from the Internet or from any remote sources are restricted from reading and writing files and making network connections on client host systems. They are also restricted from starting other programs, loading libraries, or making native calls on the client host system. In general, applets downloaded from a network or remote sources are considered untrusted. An applet can be considered trusted, based on the following factors:

Applets installed on a local filesystem or executed on a localhost. Signed applets provide a way to verify that the applet is downloaded from a reliable source and can be trusted to run with the permissions granted in the policy file.

In a Web browser, a Java plug-in provides a common framework and enables secure deployment of applets in the browser using the JRE. While downloading an applet, the Java plug-in enables the browser to install all the class files and then render the applet. A security manager (SecurityManager implementation) will be automatically installed during startup whenever an applet starts running in a Java-enabled Web browser. No downloaded applets are allowed to access resources in the client host unless they are explicitly granted permission using an entry in a Java security policy file.

Example: source code for an applet named WriteFileApplet that attempts to create and to write to a file named AppletGenrtdFile in the local directory.Example: WriteFileApplet.java

import java.awt.*;import java.io.*;import java.lang.*;import java.applet.*;

public class WriteFileApplet extends Applet {

String myFile = "/tmp/AppletGenrtdFile";

Page 53: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

File f = new File(myFile); DataOutputStream dos;

public void init() {

String osname = System.getProperty("os.name"); if (osname.indexof("Windows") != -1) { myFile="C:" + file.separator + "AppletGenrtdFile"; } } public void paint(Graphics g) {

try { dos = new DataOutputStream(new BufferedOutputStream (new FileOutputStream(myFile),128)); dos.writeChars("This is an Applet generated file\n"); dos.flush(); g.drawString("Success: Writing file" + myFile, 10, 10); } catch (SecurityException se) { g.drawString("Write Failed: Security exception: " + se, 10, 10); } catch (IOException ioe) { g.drawString("Write Failed:I/O exception" + ioe, 10, 10); } }}

To run the applet, you need to compile the source code using javac and then you may choose to deploy this applet class along with an HTML page in a Web server. To do so, create an HTML file (see Example 3-11) called WriteFileApplet.html.Example 3-11. WriteFileApplet.html

<html><head><title> Core Security Patterns Example: Applet Security</title></head><body><h1> WriteFileApplet: Writing Files in the Client host </h1><hr><APPLET CODE = WriteFileApplet.class WIDTH=400 HEIGHT=40></APPLET>

Page 54: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

<hr></body></html>

To execute this applet using an appletviewer, run the following :

appletviewer http://coresecuritypatterns.com/WriteFileApplet.html

When executing this applet, you should receive the SecurityException in the applet window. This applet shouldn't be able to write the file, because it does not have a security policy with a file permission to write in the user's home directory.

Now, let's use the following policy file WriteAppletPolicy, which grants a write permission. To do so, create a policy file (see Example 3-12) called WriteAppletPolicy.policy in the working directory:Example 3-12. WriteAppletPolicy.policy

grant { permission java.io.FilePermission "<<ALL FILES>>","write";};

To test the applet using an appletviewer, you may choose to use the -J-Djava.security.policy=WriteAppletPolicy.policy option on the JVM command line, or you can explicitly specify your policy file in the JVM security properties file in the <JAVA_HOME>/jre/lib/security directory:

policy.url.3=file:/export/xyz/WriteAppletpolicy.policy

Example 3-13 shows running the WriteFileApplet applet with the WriteAppletPolicy policy file from the command-line interface.Example 3-13. Running appletviewer using a Java security policy

appletviewer -J-Djava.security.policy=WriteAppletPolicy.policy http://coresecuritypatterns.com/WriteFileApplet.html

You should be able to run the WriteFileApplet applet successfully without a SecurityException, and it should also be able to create and write the file AppletGenrtdFile in the client's local directory.

Now let's explore the concept of signed applets.

Page 55: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Signed Applets

The Java 2 platform introduced the notion of signed applets. Signing an applet ensures that an applet's origin and its integrity are guaranteed by a certificate authority (CA) and that it can be trusted to run with the permissions granted in the policy file. The J2SE bundle provides a set of security tools that allows the end users and administrators to sign applets and applications, and also to define local security policy. This is done by attaching a digital signature to the applet that indicates who developed the applet and by specifying a local security policy in a policy file mentioning the required access to local system resources.

The Java 2 platform requires an executable applet class to be packaged into a JAR file before it is signed. The JAR file is signed using the private key of the applet creator. The signature is verified using its public key by the client user of the JAR file. The public key certificate is sent along with the JAR file to any client recipients who will use the applet. The client who receives the certificate uses it to authenticate the signature on the JAR file. To sign the applet, we need to obtain a certificate that is capable of code signing. For all production purposes, you must always obtain a certificate from a CA such as VeriSign, Thawte, or some other CA.

The Java 2 platform introduced new key management tools to facilitate support for creating signed applets:

The keytool is used to create pairs of public and private keys, to import and display certificate chains, to export certificates, and to generate X.509 v1 self-signed certificates.The jarsigner tool is used to sign JAR files and also to verify the authenticity of the signature(s) of signed JAR files.The policytool is used to create and modify the security policy configuration files.

Let's take a look at the procedure involved in creating a signed applet using our previous WriteFileApplet applet example. The following steps are involved on the originating host environment responsible for developing and deploying the signed applet:Compile the Applet source code to an executable class. Use the javac command to compile the WritefileApplet.java class. The output from the javac command is the WriteFileApplet.class.

javac WriteFileApplet.java

Package the compiled class into a JAR file. Use the jar utility with the cvf option to create a new JAR file with verbose mode (v), and specify the archive file name (f).

jar cvf WriteFileApplet.jar WriteFileApplet.class

Page 56: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Generate key pairs. Using the keytool utility, create the key pair and self-signed certificate (for testing purposes only). The JAR file is signed with the creator's private key and the signature is verified by the communicating peer of the JAR file with the public key in the pair.

keytool -genkey -alias signapplet -keystore mykeystore -keypass mykeypass -storepass mystorepass

This keytool -genkey command generates a key pair that is identified by the alias signapplet. Subsequent keytool commands are required to use this alias and the key password (-keypass mykeypass) to access the private key in the generated pair. The generated key pair is stored in a keystore database called mykeystore (-keystore mykeystore) in the current directory and is accessed with the mystorepass password (-storepass mystorepass). The command also prompts the signer to input information about the certificate, such as name, organization, location, and so forth. Sign the JAR file. Using the jarsigner utility sign the JAR file and verify the signature on the JAR files.Example: Signing an applet using jarsigner tool

jarsigner -keystore mykeystore -storepass mystorepass -keypass mykeypass -signedjar SignedWriteFileApplet.jar WriteFileApplet.jar signapplet

The -storepass mystorepass and -keystore mykeystore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass mykeypass option is the password to the private key, SignedWriteFileApplet.jar is the name of the signed JAR file, and signapplet is the alias to the private key. jarsigner extracts the certificate from the keystore and attaches it to the generated signature of the signed JAR file.

Export the public key certificate. The public key certificate will be sent with the JAR file to the end user who will use it to authenticate the signed applet. To have trusted interactions, the end user must have a copy of those public keys in its keystore. This is accomplished by exporting the public key certificate from the originating JAR signer keystore as a binary certificate file and then importing it into the client's keystore as a trusted certificate. Using the keytool, export the certificate from mykeystore to a file named mycertificate.cer as follows:

keytool -export -keystore mykeystore -storepass mystorepass -alias signapplet -file mycertificate.cer

Page 57: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Deploy the JAR and certificate files. They should be deployed to a distribution directory on a Web server. Additionally, create a Web page embedding the applet and the JAR. As shown in Example 3-15, the applet tag must use the following syntax. Example 3-15. Deploying a signedapplet Jar

<applet code=WriteFileApplet.class archive="SignedWriteFileApplet.jar" codebase="/export/home/ws/" width=400 height=40> </applet>

In addition to the previous steps, the following steps are involved in the client's environment:

Import certificate as a trusted certificate. To download and execute the signed applet, you must import the trusted public key certificate (provided by the issuer) into a keystore database. The Java runtime will use this client-side keystore to store its trusted certificates and to authenticate the signed applet. Using the Keytool utility, import the trusted certificate provided by the issuer (see Example 3-16). Example 3-16. Importing a certificate

keytool -import -alias clientcer –file mycertificate.cer -keystore clientstore -storepass clientpass

Create the policy file. Create a policy file client.policy, which grants the applet to have permission for creating and writing to the file "AppletGenrtdFile" in the client's local directory (see Example 3-17). Example 3-17. Sample policy file (Client.policy)

keystore "/export/home/clientstore"; grant SignedBy "clientcer" { permission java.io.FilePermission "<<ALL FILES>>", "write"; };

Run and test the applet using appletviewer. The appletviewer tool runs the HTML document specified in the URL, which displays the applet in its own window. To run the applet using the client policy file, enter the following at the command line (see Example 3-18). Example 3-18. Testing the applet using the client policy

appletviewer -J-Djava.security.policy=client.policy http://coresecuritypatterns.com/SignedWriteFileApplet.htmlWhat Applets Can and Cannot Do

Page 58: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Java applets are loaded on a client when the user visits a page containing an applet. The security model behind Java applets has been designed with the goal of protecting the user from malicious applets.

Applets are either sandbox applets or privileged applets. Sandbox applets are run in a security sandbox that allows only a set of safe operations. Privileged applets can run outside the security sandbox and have extensive capabilities to access the client.

Applets that are not signed are restricted to the security sandbox, and run only if the user accepts the applet. Applets that are signed by a certificate from a recognized certificate authority can either run only in the sandbox, or can request permission to run outside the sandbox. In either case, the user must accept the applet's security certificate, otherwise the applet is blocked from running.

It is recommended that you launch your applet using Java Network Launch Protocol (JNLP) to leverage expanded capabilities and improve user experience. See Deploying an Applet for step by step instructions on applet deployment.

It is recommended that you deploy your applets to a web server, even for testing. To run applets locally, add the applets to the exception site list, which is managed from the Security tab of the Java Control Panel.

In this topic we will discuss the security restrictions and capabilities of applets.Sandbox Applets

Sandbox applets are restricted to the security sandbox and can perform the following operations:

They can make network connections to the host and port they came from. Protocols must match, and if a domain name is used to load the applet, the domain name must be used to connect back to the host, not the IP address. They can easily display HTML documents using the showDocument method of the java.applet.AppletContext class. They can invoke public methods of other applets on the same page. Applets that are loaded from the local file system (from a directory in the user's CLASSPATH) have none of the restrictions that applets loaded over the network do. They can read secure system properties. See System Properties for a list of secure system properties. When launched by using JNLP, sandbox applets can also perform the following operations: They can open, read, and save files on the client. They can access the shared system-wide clipboard. They can access printing functions.

Page 59: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

They can store data on the client, decide how applets should be downloaded and cached, and much more. See JNLP API for more information about developing applets by using the JNLP API.

Sandbox applets cannot perform the following operations:

They cannot access client resources such as the local filesystem, executable files, system clipboard, and printers. They cannot connect to or retrieve resources from any third party server (any server other than the server it originated from). They cannot load native libraries. They cannot change the SecurityManager. They cannot create a ClassLoader. They cannot read certain system properties. See System Properties for a list of forbidden system properties.

Privileged applets

Privileged applets do not have the security restrictions that are imposed on sandbox applets and can run outside the security sandbox.Note: JavaScript code is treated like unsigned code. When a privileged applet is accessed from JavaScript code in an HTML page, the applet is executed within the security sandbox. This implies that the privileged applet essentially behaves likes a sandbox applet.

Solving Common Applet Problems

This section covers some common problems that you might encounter when writing Java applets. After each problem is a list of possible reasons and solutions.

Problem: My applet does not display.

Check the Java Console log for errors. Check the syntax of the applet's Java Network Launch Protocol (JNLP) file. Incorrect JNLP files are the most common reason for failures without obvious errors. Check the JavaScript syntax if deploying using the runApplet function of the Deployment Toolkit. See Deploying an Applet for details.

Problem: The Java Console log displays java.lang.ClassNotFoundException.

Page 60: vivekit.weebly.comvivekit.weebly.com/uploads/4/8/1/4/48149…  · Web view · 2017-04-10UNIT-V. GUI Programming with java. Java AWT (Abstract Window Toolkit) is an API to develop

Make sure your Java source files compiled correctly. If deploying using the <applet> tag, check that the path to the applet JAR file is specified accurately in the archive attribute. If launching using a JNLP file, check the path in the jar tag in the JNLP file. Make sure the applet's JAR file, JNLP file, and web page are located in the correct directory and reference each other accurately.

Problem: I was able to build the code once, but now the build fails even though there are no compilation errors.

Close your browser and run the build again. The browser most likely has a lock on the JAR file, because of which the build process is unable to regenerate the JAR file.

Problem: When I try to load a web page that has an applet, my browser redirects me to www.java.com without any warning

The applet on the web page is most likely deployed using the Deployment Toolkit script. The applet may require a later version of the Java Runtime Environment software than the version that currently exists on the client. Check the minimumVersion parameter of the runApplet function in the applet's web page. See Deploying an Applet for details.

Problem: I fixed some bugs and re-built my applet's source code. When I reload the applet's web page, my fixes are not showing up.

You may be viewing a previously cached version of the applet. Close the browser. Open the Java Control Panel and delete temporary internet files. This will remove your applet from cache. Try viewing your applet again.