0% found this document useful (0 votes)
18 views

Java - 5

Uploaded by

athirai12211
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Java - 5

Uploaded by

athirai12211
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

UNIT - V

WORKING WITH APPLETS,


AWT AND SWINGS

5.1 APPLETS

5.1.1 Applet fundamentals

An applet is a small Java program that is embedded and ran in


some other Java interpreter program such as

OO a Java technology-enabled browser

OO Sun’s applet viewer program called appletviewer

Applets do not use the main() method for initiating the execution
of the code. Applets when loaded automatically call certain methods
of Applet class to start and execute the applet code. Applets cannot
run any program from the local computer and they are restricted from
using libraries from other languages such as C or C++.

The general form is as shown below:

import java.awt.*;
import java.applet.*;
public class appletclassname extends Applet
{
public void paint(Graphics g)
{
//Applet operations code
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
5.2 Java Programming
Example
Applets001.java
import javax.swing.JApplet;
import java.awt.*;
public class Applets001 extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.black);
g.fillOval(60, 40, 220, 220);
g.setColor(Color.red);
g.fillOval(80, 60, 180, 180);
}
}
Applets001.html
<HTML>
<HEAD>
<TITLE>This is my first Applet</TITLE>
</HEAD>
<BODY>
<APPLET code="Applets001.class" codebase="."
width=400 height=300></APPLET>
</BODY>
</HTML>
Output

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.3
5.1.2 Applet class

Applet is a Java program that can be transported over the internet


and executed by a Java-enabled web-browser(if a browser is supporting
the applets) or an applet can be executed using the appletviewer utility
provided with JDK. An applet created using the Applet class, which
is a part of java.applet package. Applet class provides several useful
methods to give you full control over the execution of an applet.

There are two types of the applet

OO Applets based on the AWT(Abstract Window Toolkit)


package by extending its Applet class.

OO Applets based on the Swing package by extending its JApplet


class

At present, some modern versions of browsers like Google


Chrome and Mozilla Firefox have stopped supporting applets, hence
applets are not displayed or viewed with these browsers although some
browsers like Internet Explorer and Safari are still supporting applets.
Table 5.1 : Some methods of Applet class

Methods Description
void init() The first method to be called when
an applet begins its execution.
void start() Called automatically after init()
method to start the execution of
an applet.
void stop() Called when an applet has to
pause/stop its execution.
void destoy() Called when an appLet us finally
terminated.
String getParameter(String Returns the value of a parameter
ParameterName) defined in an applet

M.BALASUBRAMANIAN /AP/HOD OF CS
5.4 Java Programming

Image getImage(URL url) Returns an Image object that


contains an image specified at
location, url
void play(URL url Plays an audio clip found at the
specified at location, url
showStatus(String str) Shows a message in the status
window of the browser or
appletviewer.
The stop() method is always called before destroy() method.
Applet class is used to

OO Get applet parameters

OO Get the network location of the HTML file that contains the
applet

OO Get the network location of the applet class directory

OO Print a status message in the browser

OO Fetch an image

OO Fetch an audio clip

OO Play an audio clip

OO Resize the applet

Additionally, the Applet class provides an interface through


which the viewer or browser obtains information about the applet and
controls the applet's execution.

OO Request information about the author, version, and copyright


of the applet

OO Request a description of the parameters the applet recognizes

OO Initialize the applet

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.5
OO Destroy the applet

OO Start the applet's execution

OO Stop the applet's execution

The Applet class provides default implementations of each of


these methods. Those implementations may be overridden as necessary.

5.1.3 Applet life cycle

In Java, an applet is a special type of program embedded in the


web page to generate dynamic content. Applet is a class in Java. The
applet life cycle can be defined as the process of how the object is
created, started, stopped, and destroyed during the entire execution of
its application. It basically has five core methods namely init(), start(),
stop(), paint() and destroy().These methods are invoked by the browser
to execute. Along with the browser, the applet also works on the client
side, thus having less processing time.

init( )

Born
state

Start( ) Stop( )

Run
state Idle
state

Start( ) Destory( )

Dead
state

Fig 5.1 : Methods of Applet Life Cycle


M.BALASUBRAMANIAN /AP/HOD OF CS
5.6 Java Programming

There are five methods of an applet life cycle, and they are:

OO init(): The init() method is the first method to run that


initializes the applet. It can be invoked only once at the time of
initialization. The web browser creates the initialized objects,
i.e., the web browser (after checking the security settings) runs
the init() method within the applet.

OO start(): The start() method contains the actual code of the


applet and starts the applet. It is invoked immediately after
the init() method is invoked. Every time the browser is loaded
or refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from
one tab to another in the browser. It is in an inactive state until
the init() method is invoked.

OO stop(): The stop() method stops the execution of the applet.


The stop () method is invoked whenever the applet is stopped,
minimized, or moving from one tab to another in the browser,
the stop() method is invoked. When we go back to that page,
the start() method is invoked again.

OO destroy(): The destroy() method destroys the applet after its


work is done. It is invoked when the applet window is closed
or when the tab containing the webpage is closed. It removes
the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.

OO paint(): The paint() method belongs to the Graphics class in


Java. It is used to draw shapes like circle, square, trapezium,
etc., in the applet. It is executed after the start() method and
when the browser or applet windows are resized.

Sequence of method execution when an applet is executed.

1. init()

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.7
2. start()

3. paint()

4. stop()

5. destroy()

Syntax of entire Applet Life Cycle in Java

class TestAppletLifeCycle extends Applet


{
public void init()
{
// initialized objects
}
public void start()
{
// code to start the applet
}
public void paint(Graphics graphics)
{
// draw the shapes
}
public void stop()
{
// code to stop the applet
}
public void destroy()
{
// code to destroy the applet
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
5.8 Java Programming
5.1.4 Steps for developing an applet program

1. Import java.applet.Applet package.

2. Choose the user defined class that must extends java.applet.


Applet class and ensure the modifier of the class must be
public.

3. Overwrite the life cycle methods of the applet if require.

4. Save the program and compile.

5. Run the applet: To run the applet we have two ways. They are
using HTML program and using applet viewer tool.

Syntax

<applet code =”.class file of the applet” height = height value width
= widthvalue>

</applet>

Example
File name: MyApp.html
<HTML>
<HEAD>
<TITLE> My applet example </TITLE>
</HEAD>
<BODY>
<APPLET code="MyApp" height=100 width=150> </APPLET>
</BODY>
</HTML>
Using appletviewer

Appletviewer is a tool supplied by SUN micro system to run the


applet programs from the command prompt (in the case of browser is
not supporting).

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.9
Syntax

appletviewer filename.java

Example

appletviewer MyApp.java

When we use appletviewer to run the above applet, MyApp.java


program must contain the following tag within the multi line comment.
/*<applet code= “MyApp” height=300 width=300> </ap-
plet>*/
import java.applet.Applet;
public class MyApp extends Applet
{
public void paint(java.awt.Graphics g)
{
g.drawString ("AshaKrishna MyLove", 20,
15);
}
};
In the Graphics class we have the following method which will set
the font.

Syntax: Font f=new Font (“arial”, Font.BOLD, 40);

Example
import java.applet.*;
import java.awt.*;
/*<applet code="MyApp1" height=300 width=300> </ap-
plet>*/
public class MyApp1 extends Applet
{
String s=" ";
public void init ()
{

M.BALASUBRAMANIAN /AP/HOD OF CS
5.10 Java Programming
setBackground (Color.green);
setForeground (Color.red);
s=s+" INIT ";
}
public void start ()
{
s=s+" START ";
}
public void stop ()
{
s=s+" STOP ";
}
public void destroy ()
{
s=s+" DESTROY ";
}
public void paint (Graphics g)
{
Font f=new Font ("arial", Font.
BOLD, 40);
g.setFont (f);
g.drawString (s,100,100);
}
};
5.1.5 Passing values through parameters

To pass some parameters to an applet and how to read those


parameters in an applet to display their values in the output.

Steps to accomplish this task

OO To pass the parameters to the Applet we need to use the param


attribute of <applet> tag.

OO To retrieve a parameter's value, we need to use the


getParameter() method of Applet class.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.11
Signature of the getParamter() method

public String getParameter(String name)

OO Method takes a String argument name, which represents the


name of the parameter which was specified with the param
attribute in the <applet> tag.

OO Method returns the value of the name parameter(if it was


defined) else null is returned.

In the upcoming code, we are going to pass a few parameters like


Name, Age, Sport, Food, Fruit, Destination to the applet using param
attribute in <applet>. We will retrieve the values of these parameters
using getParameter() method of Applet class.

Example
import java.awt.*;
import java.applet.*;
/* <applet code="Applet8" width="400" height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination" value="California">
</applet>
*/
public class Applet8 extends Applet
{
String name;
String age;
String sport;
String food;
String fruit;
String destination;

M.BALASUBRAMANIAN /AP/HOD OF CS
5.12 Java Programming
public void init()
{
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
}
public void paint(Graphics g)
{
g.drawString("Reading parameters passed to
this applet -", 20, 20);
g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60);
g.drawString("Favorite fruit -" + fruit, 20,
80);
g.drawString("Favorite food -" + food, 20,
100);
g.drawString("Favorite destination -" + name,
20, 120);
g.drawString("Favorite sport -" + sport, 20,
140);
}
Output

appletviewer Applet8.java

Where Applet8.java is the name of java file that contains the code
of an applet. Right after running the applet program using appletviewer
a new applet window is displayed to us -

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.13

5.1.6 Graphics in an applet

java.awt.Graphics class provides many methods for graphics


programming. Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is


used to draw the specified string.

2. public void drawRect(int x, int y, int width, int height):


draws a rectangle with the specified width and height.

3. public abstract void fillRect(int x, int y, int width, int


height): is used to fill rectangle with the default color and
specified width and height.

4. public abstract void drawOval(int x, int y, int width, int


height): is used to draw oval with the specified width and
height.

5. public abstract void fillOval(int x, int y, int width, int


height): is used to fill oval with the default color and specified
width and height.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.14 Java Programming
6. public abstract void drawLine(int x1, int y1, int x2, int y2):
is used to draw line between the points(x1, y1) and (x2, y2).

7. public abstract boolean drawImage(Image img, int x, int y,


ImageObserver observer): is used draw the specified image.

8. public abstract void drawArc(int x, int y, int width, int


height, int startAngle, int arcAngle): is used draw a circular
or elliptical arc.

9. public abstract void fillArc(int x, int y, int width, int height,


int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.

10. public abstract void setColor(Color c): is used to set the


graphics current color to the specified color.

11. public abstract void setFont(Font font): is used to set the


graphics current font to the specified font.

Example of Graphics in applet


import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.15
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300"
height="300"> </applet>
</body>
</html>
5.1.7 Event-handling

An event in a java program is generated upon clicking a button,


typing in a textfield, checking a checkbox or radio box, selecting an
item in a drop down list etc. In this article we will understand how such
events are handled, when generated from within an applet window.

In order to handle such events, we need to register our program to


listen such events when they are generated by our program, during its
execution.

To register program to listen events

To listen events, we must implement interfaces related to the


kind of event that is generated by our program. For example, if our
program has a button in it and in order to listen a button click event, we
must implement ActionListener interface and implement its method
actionPerformed(), which gives us the name of the button that was
clicked, that lead to a button click event.

Event handling in Applet


In the forthcoming code, we have created an applet named Applet2
by extending the Applet class, besides this we have also implemented

OO ActionListener interface and have implemented its


actionPerformed() method to listen to button click events or
when an Enter key is pressed in a textfield within our program.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.16 Java Programming
OO ItemListener interface and have implemented its
itemStateChanged() method to listen to checking/unchecking
of checkboxes or radio boxes in our program.
Applet2.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Applet2" width=250 height=200> </ap-
plet> */
public class Applet2 extends Applet implements Ac-
tionListener, ItemListener
{
Label label1, label2, label3;
TextField tf1, tf2, tf3;
Checkbox ck1, ck2;
CheckboxGroup cb;
public void init()
{
System.out.println("Initializing an applet");
label1 = new Label("Enter your name");
tf1= new TextField(10);
label2 = new Label("Enter your city");
tf2= new TextField(10);
label3 = new Label("Gender");
cb= new CheckboxGroup();
ck1 = new Checkbox("Male",cb,false);
ck2 = new Checkbox("Female",cb,false);
add(label1);
add(tf1);
add(label2);
add(tf2);
add(label3);
add(ck1);
add(ck2);
tf1.addActionListener(this);
tf2.addActionListener(this);
ck1.addItemListener(this);
ck2.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.17
{
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Your name is "+ tf1.get
Text(), 10, 150 );
g.drawString("Your city is "+ tf2.get
Text(), 10,170 );
if(cb.getSelectedCheckbox()!=null)
{
g.drawString("Your gender is "+ cb.get
SelectedCheckbox().getLabel(), 10,190);
}
}
}
Output

appletviewer Applet2.java

M.BALASUBRAMANIAN /AP/HOD OF CS
5.18 Java Programming
5.2 GUI APPLICATIONS - PART 1

5.2.1 Graphical User Interface

In Java applications, the components that comprise a GUI


(Graphical User Interface) are stored in containers called forms. The
Java language provides a set of user interface components from which
GUI forms can be built. The IDE's GUI Builder assists you in designing
and building Java forms by providing a series of tools that simplify the
process.

GUI (Graphical User Interface) in Java is an easy-to-use visual


experience builder for Java applications. It is mainly made of graphical
components like buttons, labels, windows, etc. through which the user
can interact with an application. GUI plays an important role to build
easy interfaces for Java applications.

IDE's Java GUI Tools

The IDE provides several tools to simplify the process of building


GUIs:

OO GUI Builder. The primary workspace within which GUI


design takes place in the IDE. The GUI Builder enables you to
lay out forms by placing components where you want them and
by providing visual feedback in the form of guidelines.

OO Navigator window. Displays a tree hierarchy of all components


contained in the currently opened form. Displayed items
include visual components and containers, such as buttons,
labels, menus, and panels, as well as non-visual components
such as timers and data sources.

OO Palette window. A list containing all the components that can


be added to forms. You can customize the window to display
its contents as icons only, or as icons with component names.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.19
OO Properties window. Displays the editable settings for the
currently selected component.

OO Connection wizard. Assists in setting events between


components in a form without the need of writing code
manually.

OO Manager. Enables you to add, remove, and organize window


components such as Swing components, AWT components,
Layouts, and beans.

In addition, the IDE provides support for the Beans Binding


specification which provides a way to synchronize the values of
different bean properties. This support also simplifies the creation of
desktop database applications.

5.2.2 Creating windows

A Frame is a top-level window with a title and a border. The size of


the frame includes any area designated for the border. The dimensions
of the border area may be obtained using the getInsets method.
Since the border area is included in the overall size of the frame, the
border effectively obscures a portion of the frame, constraining the
area available for rendering and/or displaying subcomponents to the
rectangle which has an upper-left corner location of (insets.left, insets.
top), and has a size of width - (insets.left + insets.right) by height -
(insets.top + insets.bottom).

A frame, implemented as an instance of the JFrame class, is a


window that has decorations such as a border, a title, and supports
button components that close or iconify the window. Applications
with a GUI usually include at least one frame. Applets sometimes
use frames, as well. To make a window that is dependent on another
window disappearing when the other window is iconified, for example
use a dialog instead of frame. To make a window that appears within
another window, use an internal frame.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.20 Java Programming
Creating and Showing Frames

Here is a picture of the extremely plain window created by the


FrameDemo demonstration application.

The following FrameDemo code shows how to create and set up


a frame.
1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
2. Optional
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3. Create components and put them in the frame.
frame.getContentPane().add(emptyLabel,BorderLayout.CENTER);
4. Size the frame.
frame.pack();
5. Show it.
frame.setVisible(true);
Specifying Window Decorations

OO By default, window decorations are supplied by the native


window system. However, you can request that the look-and-
feel provide the decorations for a frame.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.21
OO You can also specify that the frame have no window decorations
at all, a feature that can be used on its own, or to provide your
own decorations, or with full-screen exclusive mode.

OO If the window system supports minimization, then the icon


is used to represent the minimized window. Most window
systems or look and feels also display the icon in the window
decorations. A typical icon size is 16x16 pixels, but some
window systems use other sizes.

OO The following snapshots show three frames that are identical


except for their window decorations. The first uses decorations
provided by the window system, which happen to be Microsoft
Windows, but could as easily be any other system running the
Java platform.

OO The second and third use window decorations provided by the


Java look and feel.

OO The third frame uses Java look and feel window decorations,
but has a custom icon.

Window decorations provided by the look and feel W i n d o w

M.BALASUBRAMANIAN /AP/HOD OF CS
5.22 Java Programming
decorations provided by the window system Custom icon;
window decorations provided by the look and feel

Here is an example of creating a frame with a custom icon and


with window decorations provided by the look and feel:
//Ask for window decorations provided by the look and feel.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
The value you set with setDefaultLookAndFeelDecorated
is used for all subsequently created JFrames. You can switch
back to using window system decorations by invoking JFrame.
setDefaultLookAndFeelDecorated(false). Some look and feels might
not support window decorations; in this case, the window system
decorations are used.
5.2.3 Dialog boxes

The JOptionPane class is used to provide standard dialog boxes


such as message dialog box, confirm dialog box and input dialog box.
These dialog boxes are used to display information or get input from
the user. The JOptionPane class inherits JComponent class.

Declaration

public class JOptionPane extends JComponent implements


Accessible.

Table 5.2 : Common Constructors of JOptionPane

Constructor Description
JOptionPane() It is used to create a JOptionPane
with a test message.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.23
JOptionPane(Object message) It is used to create an instance
of JOptionPane to display a
message.
JOptionPane(Object message, int It is used to create an instance
messageType of JOptionPane to display a
message with specified message
type and default options.

Table 5.3 : Common Methods of JOptionPane class

Methods Description
JDialog createDialog(String title) It is used to create and return a
new parentless JDialog with the
specified title.
static void It is used to create an information-
showMessageDialog(Component message dialog titled "Message".
parentComponent, Object
message)
static void It is used to create a message
showMessageDialog(Component dialog with given title and
parentComponent, Object message, messageType.
String title, int messageType)
static int It is used to create a dialog with
showConfirmDialog(Component the options Yes, No and Cancel;
parentComponent, Object with the title, Select an Option.
message)
static String It is used to show a question-
showInputDialog(Component message dialog requesting
parentComponent, Object input from the user parented to
message) parentComponent.
void setInputValue(Object It is used to set the input value
newValue) that was selected or input by the
user.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.24 Java Programming
Java JOptionPane Example: showMessageDialog()
import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample()
{
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello,
Welcome to Javatpoint.");
}
public static void main(String[] args)
{
new OptionPaneExample();
}
}
Output

Java JOptionPane Example: showMessageDialog()


import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample()
{
f=new JFrame();
JOptionPane.showMessageDialog(f,"

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.25
Successfully Updated.","Alert",
JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args)
{
new OptionPaneExample();
}

Output

Java JOptionPane Example: showInputDialog()


import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample()
{
f=new JFrame();
String name=JOptionPane.showInputDia
log(f,"Enter Name");
}
public static void main(String[] args)
{
new OptionPaneExample();
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
5.26 Java Programming
Output

Java JOptionPane Example: showConfirmDialog()


import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample extends WindowAdapter
{
JFrame f;
OptionPaneExample()
{
f=new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_
NOTHING_ON_ CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e)
{
inta=JOptionPane.showConfirmDialog(f,"Are
you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_
ON_CLOSE);
}
public static void main(String[] args)

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.27
{
new OptionPaneExample();
}
}
Output

5.2.4 Layout managers

OO Layout managers enable you to control the way in which visual


components are arranged in GUI forms by determining the size
and position of components within containers.

OO This is accomplished by implementing the LayoutManager


interface. By default, new forms created with the GUI Builder
use the GroupLayout layout manager. The IDE has special
support for GroupLayout called Free Design.

OO Free Design enables you to lay out your form using visual
guidelines that automatically suggest optimal alignment
and spacing of components. As you work, the GUI Builder
translates your design decisions into a functional UI without
requiring you to specify a layout manager.

OO Because Free Design employs a dynamic layout model,

M.BALASUBRAMANIAN /AP/HOD OF CS
5.28 Java Programming
whenever you resize the form or switch locales the GUI
adjusts to accommodate your changes without changing the
relationships between components.

OO You can combine FreeDesign containers and containers using


other layout managers together in the same form.

GroupLayout was added to version 6 of the Java Platform. If


you must deploy your application to version 5 of the Java Platform,
you must use the version of GroupLayout that is in the Swing Layout
Extensions library. You can set the version of GroupLayout in the
property sheet for each form. With the form selected in the Design
view, select the form's root node in the Navigator window, and change
the Layout Generation Style property. New containers added to forms
created in earlier versions of the IDE do not assume the FreeDesign
layout manager in order to ensure code compatibility. However, it can
be set manually in the Set Layout submenu.

Layout Managers in the IDE

FlowLayout

FlowLayout arranges components in a container like words on a


page. It fills the top line from left to right until no more components
can fit, continuing the same way on each successive line below.

BorderLayout

BorderLayout arranges components along the edges or the middle


of their container. Use BorderLayout to place components in five
possible positions: North, South, East, West, and Center corresponding
to the container's top, bottom, right and left edges and interior area.

GridLayout

GridLayout places components in a grid of equally sized cells,


adding them to the grid from left to right and top to bottom.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.29
GridBagLayout

GridBagLayout is a powerful layout manager that provides precise


control over all aspects of the layout even when the container is resized,
using a complex set of component properties called "constraints." It
is particularly useful for multiplatform Java applications as it enables
you to create a free-form layout that maintains a consistent appearance
across platforms.

GridBagLayout places components in a grid of rows and columns


in which grid cells do not all have to be the same size. In addition,
components can span multiple rows, columns, or both. For more
information about using GridBagLayout see Section 10.3.2, "How to
Use the GridBag Customizer."

CardLayout

CardLayout provides a means of managing two or more


components occupying the same display area. When using CardLayout
each component is like a card in a deck, where all cards are the same
size and only the top card is visible at any time. Since the components
share the same display space, at design time you must select individual
components using the Navigator window.

BoxLayout

BoxLayout allows multiple components to be arranged either


vertically or horizontally, but not both. Components managed by
BoxLayout are arranged from left to right or top to bottom in the order
they are added to the container. Components in BoxLayout do not wrap
to a second row or column when more components are added or even
when the container is resized.

AbsoluteLayout

AbsoluteLayout is a layout manager that is provided with the


IDE. AbsoluteLayout enables components to be placed exactly where

M.BALASUBRAMANIAN /AP/HOD OF CS
5.30 Java Programming
you want them in the form, move them around in the IDE, and resize
them using their selection borders. It is particularly useful for making
prototypes since there are no formal limitations and you do not have
to enter any property settings. However, it is not recommended
for production applications since the fixed locations and sizes of
components do not change with the environment.

Null Layout

The Null Layout is used to design forms without any layout


manager at all. Like the AbsoluteLayout, it is useful for making quick
prototypes but is not recommended for production applications, as
the fixed locations and sizes of components do not change when the
environment changes.

How to Set the Layout Manager

When you create a new container, it is generally created using


GroupLayout so that you can take advantage of the IDE's Free Design
features. If necessary, you can change the layout of most containers
using the window, GUI Builder, or Navigator window.

To set the layout manager from the GUI Builder:

1. Right-click the container whose layout you wish to change.

2. In the contextual menu, choose the desired layout from the


Set Layout submenu. The IDE applies the specified layout
manager to the selected container.

To set the layout manager from the Navigator window:

1. Right-click the node for the container whose layout you wish to
change.

2. In the contextual menu, choose the desired layout from the Set
Layout submenu.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.31
5.2.5 AWT component classes

OO Java AWT (Abstract Window Toolkit) is an API to develop


Graphical User Interface (GUI) or windows-based applications
in Java.

OO Java AWT components are platform-dependent i.e. components


are displayed according to the view of operating system.

OO AWT is heavy weight i.e. its components are using the resources
of underlying operating system (OS).

OO AWT components in java are platform-dependent components


that mean a display of components on a graphical user interface
depends on the underlying operating system

OO AWT components are generally heavy components that make


high use of operating system resources.

Syntax

import java.awt.*;

class <className> extends Frame

<className>()

Button button=new Button("<Text_To_Display_


On_Button>");

button.setBounds(40,90,80,30);// call method to set


button position

add(button);// adding component to the container

setSize(400,400);//set size of container

M.BALASUBRAMANIAN /AP/HOD OF CS
5.32 Java Programming
setVisible(true);//set visibility of container to true

public static void main(String args[])

<className> clsobj=new <className>();

The above syntax shows how to use a Button component of the


AWT package. In the above syntax <ClassName> denotes name of
java class. <Text_To_Display_On_Button> can be set according to our
functionality.

The java.awt package provides classes for AWT API such as

OO TextField

OO Label

OO TextArea

OO RadioButton, CheckBox

OO Choice

OO List

AWT is platform independent


Java AWT calls the native platform calls the native platform
(operating systems) subroutine for creating API components like
TextField, ChechBox, button, etc. For example, an AWT GUI with
components like TextField, label and button will have different look
and feel for the different platforms like Windows, MAC OS, and Unix.
The reason for this is the platforms have different view for their native

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.33
components and AWT directly calls the native subroutine that creates
those components. In simple words, an AWT application will look like
a windows application in Windows OS whereas it will look like a Mac
application in the MAC OS.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Fig 5.2 : Java AWT Hierarchy

Components

All the elements like the button, text fields, scroll bars, etc. are
called components. In Java AWT, there are classes for each component

M.BALASUBRAMANIAN /AP/HOD OF CS
5.34 Java Programming
as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.

Container

The Container is a component in AWT that can contain another


components like buttons, textfields, labels etc. The classes that extends
Container class are known as container such as Frame, Dialog and
Panel. It is basically a screen where the where the components are
placed at their specific locations. Thus it contains and controls the
layout of components.

Types of containers

There are four types of containers in Java AWT:

1. Window

2. Panel

3. Frame

4. Dialog

Window

The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window.
We need to create an instance of Window class to create this container.

Panel

The Panel is the container that doesn't contain title bar, border or
menu bar. It is generic container for holding the components. It can
have other components like button, text field etc. An instance of Panel
class creates a container, in which we can add components.

Frame

The Frame is the container that contain title bar and border and can

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.35
have menu bars. It can have other components like button, text field,
scrollbar etc. Frame is most widely used container while developing an
AWT application.

Table 5.4 : Useful Methods of Component Class

Method Description
public void add(Component c) Inserts a component on this
component.
public void setSize(int width,int Sets the size (width and height)
height) of the component.
public void Defines the layout manager for
setLayout(LayoutManager m) the component.
public void setVisible(boolean Changes the visibility of the
status) component, by default false.

Java AWT Example


To create simple AWT example, you need a frame. There are two
ways to create a GUI using Frame in AWT.

1. By extending Frame class (inheritance)

2. By creating the object of Frame class (association)

AWT Example by Inheritance

Simple example of AWT where we are inheriting Frame class.


Here, we are showing Button component on the Frame.

AWTExample1.java
import java.awt.*;
public class AWTExample1 extends Frame
{
AWTExample1()
{
Button b = new Button("Click Me!!");

M.BALASUBRAMANIAN /AP/HOD OF CS
5.36 Java Programming
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
AWTExample1 f = new AWTExample1();
}
}
Output:

AWT Example by Association

Simple example of AWT where we are creating instance of Frame


class. Here, we are creating a TextField, Label and Button component
on the Frame.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.37
AWTExample2.java
import java.awt.*;
class AWTExample2
{
AWTExample2()
{
Frame f = new Frame();
Label l = new Label("Employee id:");
Button b = new Button("Submit");
TextField t = new TextField();
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b);
f.add(l);
f.add(t);
f.setSize(400,300);
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
AWTExample2 awt_obj = new AWTExample2();
}
}
Output:

M.BALASUBRAMANIAN /AP/HOD OF CS
5.38 Java Programming

5.2.6 Swing Component Classes

The class Component is the abstract base class for the non
menu user-interface controls of AWT. Component represents an
object with graphical representation. Java Swing tutorial 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. 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.

Class Declaration for java.awt.Component class

public abstract class Component extends Object implements


ImageObserver, MenuContainer, Serializable

Field

Following are the fields for java.awt.Component class


M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.39
OO static float BOTTOM_ALIGNMENT − Ease-of-use constant
for getAlignmentY.

OO static float CENTER_ALIGNMENT − Ease-of-use constant


for getAlignmentY and getAlignmentX.

OO static float LEFT_ALIGNMENT − Ease-of-use constant for


getAlignmentX.

OO static float RIGHT_ALIGNMENT − Ease-of-use constant


for getAlignmentX.

OO static float TOP_ALIGNMENT − Ease-of-use constant for


getAlignmentY().

Class Constructors

protected Component() - This creates a new Component.

Class Methods

This class inherits methods from the following class java.lang.


Object

Table 5.5 : Difference between AWT and Swing

Java AWT Java Swing


AWT components are platform- Java swing components are
dependent. platform-independent.
AWT components are Swing components are
heavyweight. lightweight.
AWT doesn't support pluggable Swing supports pluggable look
look and feel. and feel.
AWT provides less components Swing provides more powerful
than Swing. components such as tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.40 Java Programming

AWT doesn't follows Swing follows MVC.


MVC(Model View Controller)
where model represents data,
view represents presentation and
controller acts as an interface
between model and view.

The Java Foundation Classes (JFC) are a set of GUI components


which simplify the development of desktop applications.

Fig 5.3 : Swing Hierarchy Diagram

Table 5.6 : Important methods in Swing class

Method Description
public void add(Component c) add a component on another
component.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.41
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the
component. It is by default false.

Java Swing Examples

There are two ways to create a frame:

OO By creating the object of Frame class (association)

OO By extending Frame class (inheritance)

For example
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating in
stance of JFrame
JButton b=new JButton("click");//creat
ing 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 man
agers
f.setVisible(true);//making the frame
visible
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
5.42 Java Programming
Output

Example of Swing by Association inside constructor


import javax.swing.*;
public class Simple
{
JFrame f;
Simple()
{
f=new JFrame();//creating instance of
JFrame
JButton b=new JButton("click");//creat
ing instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500
height
f.setLayout(null);//using no layout man
agers
f.setVisible(true);//making the frame
visible
}
public static void main(String[] args)
{
new Simple();
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.43
Simple example of Swing by inheritance
import javax.swing.*;
public class Simple2 extends JFrame
{
JFrame f;
Simple2()
{
JButton b=new JButton("click");//create
button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new Simple2();
}
}
5.3 GUI APPLICATIONS PART 2:

5.3.1 Event handling

The Java programming language uses events to enable GUI form


behavior. Source objects can trigger events which one or more objects
with event listeners react to by means of event handlers.

Defining Event Handlers

You can define event handlers using a component's property sheet


or contextual menu. You can also define an event handler using the
Connection wizard.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.44 Java Programming
To define an event handler using the property sheet:

1. Select the component in the Navigator window.


2. Click the Events button at the top of the Properties window.
3. Click the value of the desired event in the list. Initially, the
value for all events is <none>. When you click the value field,
<none> is automatically replaced with the default event name.
4. Click the event's ellipsis (...) button to open the Handlers dialog
box.
5. Click the Add button to add a new name to the list of handlers.
Click OK. The code for the listener and the empty handler
method body is generated.
To define an event handler using the contextual menu:

1. Right-click a form component in the Files window, Project


window, or Navigator window.

2. Choose Events from the contextual menu and its submenus.


Bold menu items in the Events submenus indicate event
handlers that have already been defined. The code for the
listener and the empty body of the handler method is generated.
The default name is assigned to the event handler.

3. Add your code for the new event handler in the Source Editor.

To add multiple handlers for one event:

1. In the Navigator window, select the component for which you


want to add multiple handlers.

2. Click the Events button at the top of the Properties window.

3. Select the event in the property sheet and click the ellipsis (...)
button to display the Handlers dialog box. Click the Add button
and fill out the form. Repeat these steps to add additional event
handlers.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.45
To remove event handlers:

1. In the Navigator window, select the component from which


you want to remove the event handlers.

2. Click the Events button at the top of the Properties window.

3. Select the event in the property sheet and click the ellipsis (...)
button to display the Handlers dialog box. Select the unwanted
handler and click the Remove button. Alternately, go to the
Properties window and delete the name of the handler you want
to remove.

4. In the Handlers dialog box, select the unwanted handler and


click Remove.

When you remove an event handler, the corresponding code block


is deleted. If more than one handler uses the same name and same block
of code, deleting a single reference to the code does not delete the code
itself. You must delete all references to delete the corresponding code
block; a confirmation dialog box is displayed first.

5.3.2 Other AWT components

An AWT component can be considered as an object that can


be made visible on a graphical interface screen and through which
interaction can be performed.

In java.awt package, the following components are available:

1. Containers: As the name suggests, this awt component is used to


hold other components. Basically, there are the following different
types of containers available in java.awt package:

a. Window: This is a top-level container and an instance of a


window class that does not contain a border or title.

b. Frame: Frame is a Window class child and comprises the title


bar, border and menu bars. Therefore, the frame provides a resizable
M.BALASUBRAMANIAN /AP/HOD OF CS
5.46 Java Programming
canvas and is the most widely used container used for developing
AWT-based applications. Various components such as buttons, text
fields, scrollbars etc., can be accommodated inside the frame container.

Java Frame can be created in two ways:

OO By Creating an object of Frame class.

OO By making Frame class parent of our class.

Dialog: Dialog is also a child class of window class, and it provides


support for the border as well as the title bar. In order to use dialog as a
container, it always needs an instance of frame class associated with it.

Panel: It is used for holding graphical user interface components


and does not provide support for the title bar, border or menu.

Button: This is used to create a button on the user interface with a


specified label. We can design code to execute some logic on the click
event of a button using listeners.

Text Fields: This component of java AWT creates a text box of a


single line to enter text data.

Label: This component of java AWT creates a multi-line


descriptive string that is shown on the graphical user interface.
Canvas: This generally signifies an area that allows you to draw
shapes on a graphical user interface.
Choice: This AWT component represents a pop-up menu having
multiple choices. The option which the user selects is displayed on top
of the menu.
Scroll Bar: This is used for providing horizontal or vertical
scrolling feature on the GUI.

List: This component can hold a list of text items. This component
allows a user to choose one or more options from all available options
in the list.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.47
Checkbox: This component is used to create a checkbox of GUI
whose state can be either checked or unchecked.

Example of AWT Components in Java


package com.example.demo;
package com.example.demo;
import java.applet.Applet;
import java.awt.*;
public class AWTDemo extends Applet
{
public void init()
{
Button button = new Button("Click Here
to Submit");
this.add(button);
Checkbox checkbox = new Checkbox("My
Checkbox");
this.add(checkbox);
CheckboxGroup checkboxgrp = new Check
boxGroup();
this.add(new Checkbox("Check box Option
1", checkboxgrp,false));
this.add(new Checkbox("Check box Option
2", checkboxgrp,false));
this.add(new Checkbox("Check box Option
3", checkboxgrp,true));
// adding to container
Choice choice = new Choice();
choice.addItem("Choice Option 1");
choice.addItem("Choice Option 2");
choice.addItem("Choice Option 3");
this.add(choice);
Label label = new Label("Demo Label");
this.add(label);
TextField textfield = new TextField("De
moTextField", 30);
M.BALASUBRAMANIAN /AP/HOD OF CS
5.48 Java Programming
this.add(textfield);
}
}
The above program shows how to use AWT components like
buttons, Checkboxes, Checkbox group, Labels, Choice and Text Fields
in java code.

5.3.3 AWT graphics classes

The Graphics class is the abstract super class for all graphics
contexts which allow an application to draw onto components that can
be realized on various devices, or onto off-screen images as well. A
Graphics object encapsulates all state information required for the basic
rendering operations that Java supports. State information includes the
following properties.

OO The Component object on which to draw.

OO A translation origin for rendering and clipping coordinates.

OO The current clip.

OO The current color.

OO The current font.

OO The current logical pixel operation function.

OO The current XOR alternation color

Class declaration for java.awt.Graphics class

public abstract class Graphics extends Object

Class constructors

Graphics() ()

Constructs a new Graphics object.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.49
Class methods

Method & Description

abstract void clearRect(int x, int y, int width, int height)

Clears the specified rectangle by filling it with the background


color of the current drawing surface.

abstract void clipRect(int x, int y, int width, int height)

Intersects the current clip with the specified rectangle.

abstract void copyArea(int x, int y, int width, int height, int dx, int
dy)

Copies an area of the component by a distance specified by dx and dy.

abstract Graphics create()

Creates a new Graphics object that is a copy of this Graphics object.

Graphics create(int x, int y, int width, int height)

Creates a new Graphics object based on this Graphics object, but with
a new translation and clip area.

abstract void dispose()

Disposes of this graphics context and releases any system resources


that it is using.

void draw3DRect(int x, int y, int width, int height, boolean raised)

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

abstract void drawArc(int x, int y, int width, int height, int


startAngle, int arcAngle)

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


rectangle.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.50 Java Programming
void drawBytes(byte[] data, int offset, int length, int x, int y)

Draws the text given by the specified byte array, using this graphics
context's current font and color.

void drawChars(char[] data, int offset, int length, int x, int y)

Draws the text given by the specified character array, using this graphics
context's current font and color.

abstract boolean drawImage(Image img, int x, int y, Color bgcolor,


ImageObserver observer)

Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer)

Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, int width, int


height, Color bgcolor, ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit
inside the specified rectangle.

abstract boolean drawImage(Image img, int x, int y, int width, int


height, ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit
inside the specified rectangle.

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int
dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver
observer)

Draws as much of the specified area of the specified image as is


currently available, scaling it on the fly to fit inside the specified area
of the destination drawable surface.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.51
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2,
int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)

Draws as much of the specified area of the specified image as is


currently available, scaling it on the fly to fit inside the specified area
of the destination drawable surface.

abstract void drawLine(int x1, int y1, int x2, int y2)

Draws a line, using the current color, between the points (x1, y1) and
(x2, y2) in this graphics context's coordinate system.

abstract void drawOval(int x, int y, int width, int height)

Draws the outline of an oval.

abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)

Draws a closed polygon defined by arrays of x and y coordinates.

void drawPolygon(Polygon p)

Draws the outline of a polygon defined by the specified Polygon object.

abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)

Draws a sequence of connected lines defined by arrays of x and y


coordinates.

void drawRect(int x, int y, int width, int height)

Draws the outline of the specified rectangle.

abstract void drawRoundRect(int x, int y, int width, int height, int


arcWidth, int arcHeight)

Draws an outlined round-cornered rectangle using this graphics


context's current color.

abstract void drawString(AttributedCharacterIterator iterator,


int x, int y)

M.BALASUBRAMANIAN /AP/HOD OF CS
5.52 Java Programming
Renders the text of the specified iterator applying its attributes in
accordance with the specification of the TextAttribute class.

abstract void drawString(String str, int x, int y)

Draws the text given by the specified string, using this graphics
context's current font and color.

void fill3DRect(int x, int y, int width, int height, boolean raised)

Paints a 3-D highlighted rectangle filled with the current color.

abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle)

Fills a circular or elliptical arc covering the specified rectangle.

abstract void fillOval(int x, int y, int width, int height)

Fills an oval bounded by the specified rectangle with the current color.

abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)

Fills a closed polygon defined by arrays of x and y coordinates.

void fillPolygon(Polygon p)

Fills the polygon defined by the specified Polygon object with the
graphics context's current color.

abstract void fillRect(int x, int y, int width, int height)

Fills the specified rectangle.

abstract void fillRoundRect(int x, int y, int width, int height, int


arcWidth, int arcHeight)

Fills the specified rounded corner rectangle with the current color.

void finalize()

Disposes of this graphics context once it is no longer referenced.


M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.53
abstract Shape getClip()

Gets the current clipping area.

abstract Rectangle getClipBounds()

Returns the bounding rectangle of the current clipping area.

Rectangle getClipBounds(Rectangle r)

Returns the bounding rectangle of the current clipping area.

Rectangle getClipRect()

Deprecated. As of JDK version 1.1, replaced by getClipBounds().

abstract Color getColor()

Gets this graphics context's current color.

abstract Font getFont()

Gets the current font.

FontMetrics getFontMetrics()

Gets the font metrics of the current font.

abstract FontMetrics getFontMetrics(Font f)

Gets the font metrics for the specified font.

boolean hitClip(int x, int y, int width, int height)

Returns true if the specified rectangular area might intersect the current
clipping area.

abstract void setClip(int x, int y, int width, int height)

Sets the current clip to the rectangle specified by the given coordinates.

abstract void setClip(Shape clip)

M.BALASUBRAMANIAN /AP/HOD OF CS
5.54 Java Programming
Sets the current clipping area to an arbitrary clip shape.
abstract void setColor(Color c)
Sets this graphics context's current color to the specified color.
abstract void setFont(Font font)
Sets this graphics context's font to the specified font.
abstract void setPaintMode()
Sets the paint mode of this graphics context to overwrite the destination
with this graphics context's current color.
abstract void setXORMode(Color c1)
Sets the paint mode of this graphics context to alternate between this
graphics context's current color and the new specified color.

String toString()

Returns a String object representing this Graphics object's value.

abstract void translate(int x, int y)

Translates the origin of the graphics context to the point (x, y) in the
current coordinate system.

Example program
package com.example.demo;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AWTGraphicsDemo extends Frame
{
public AWTGraphicsDemo()
{
super("Java AWT Examples");
prepareGUI();
}
public static void main(String[] args)
{

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.55
AWTGraphicsDemo awtGraphicsDemo = new AWT-
GraphicsDemo();
awtGraphicsDemo.setVisible(true);
}
private void prepareGUI()
{
setSize(400,400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent win-
dowEvent)
{
System.exit(0);
}
});
}

@Override
public void paint(Graphics g)
{
g.setColor(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to learn Java", 50, 150);
}
}
Output

M.BALASUBRAMANIAN /AP/HOD OF CS
5.56 Java Programming
5.3.4 Other Swing Controls.

The swing controls in Java are

OO JLabel

OO JRadioButton

OO ButtonGroup

OO JCheckBox

OO JTextField

OO JTextArea

OO JButton

OO Border

OO JComboBox

OO JTabbedPane

OO JPasswordField

JLabel

The object of the JLabel class may be a component for putting


text during a container. It’s used to display one line of read-only text.
The text is often changed by an application but a user cannot edit it
directly. It inherits the JComponent class.

Declaration: public class JLabel extends JComponent implements


SwingConstants, Accessible

Syntax: JLabel jl = new JLabel();

JLabel Constructors

OO JLabel(): It is used to create a JLabel instance with no image


and with an empty string for the title.
M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.57
OO JLabel(String s): It is used to create a JLabel instance with the
specified text.

OO JLabel(Icon i): It is used to create a JLabel instance with the


specified image.

OO JLabel(String s, Icon I, int horizontalAlignment): It is used


to create a JLabel instance with the specified text, image, and
horizontal alignment.

Sample Program to understand JLabel Swing Control in Java:


import javax.swing.*;
import java.awt.*;
public class JLabelDemo extends JFrame
{
JLabel jl;
JLabelDemo ()
{
jl = new JLabel ("Good Morning");
Container c = this.getContentPane ();
c.setLayout (new FlowLayout ());
c.setBackground (Color.blue);
Font f = new Font ("arial", Font.BOLD,
34);
jl.setFont (f);
jl.setBackground (Color.white);
c.add (jl);
this.setVisible (true);
this.setSize (400, 400);
this.setTitle ("Label");
this.setDefaultCloseOperation (JFrame.
EXIT_ON_CLOSE);
}
public static void main (String[]args)
{

M.BALASUBRAMANIAN /AP/HOD OF CS
5.58 Java Programming
new JLabelDemo ();
}
}
Output

JRadioButton

This component allows the user to select only one item from a
group item. By using the JRadioButton component you can choose one
option from multiple options.

Declaration: public class JRadioButton extends JToggleButton


implements Accessible

Syntax: JRadioButton jrb = new JRadioButton();

JRadioButton Constructors

OO JRadioButton(): It is used to create an unselected radio button


with no text.

OO JRadioButton(Label): It is used to create an unselected radio


button with specified text.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.59
OO JRadioButton(Label, boolean): It is used to create a radio
button with the specified text and selected status.

ButtonGroup

This class is used to place multiple RadioButton into a single


group. So the user can select only one value from that group. We can
add RadioButtons to the ButtonGroup by using the add method.

Example : add(jrb);

Syntax : ButtonGroup bg = new ButtonGroup();

JCheckBox

This component allows the user to select multiple items from a


group of items. It is used to create a CheckBox. It is used to turn an
option ON or OFF.

Declaration: public class JCheckBox extends JToggleButton


implements Accessible

JCheckBox Constructors

OO JCheckBox(): It is used to create an initially unselected


checkbox button with no text, no icon.

OO JCheckBox(Label): It is used to create an initially unselected


checkbox with text.

OO JCheckBox(Label, boolean): It is used to create a checkbox


with text and specifies whether or not it is initially selected.

OO JCheckBox(Action a): It is used to create a checkbox where


properties are taken from the Action supplied.

JTextField

The JTextField component allows the user to type some text in a


single line. It basically inherits the JTextComponent class.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.60 Java Programming
Declaration: public class JTextField extends JTextComponent
implements SwingConstants

Syntax: JTextField jtf = new JTextField();

JTextField Constructors

OO JTextField(): It is used to create a new Text Field.

OO JTextField(String text): It is used to create a new Text Field


initialized with the specified text.

OO JTextField(String text, int columns): It is used to create a


new Text field initialized with the specified text and columns.

OO JTextField(int columns): It is used to create a new empty


TextField with the specified number of columns.

JTextArea

The JTextArea component allows the user to type the text in


multiple lines. It also allows the editing of multiple-line text. It basically
inherits the JTextComponent class.

Declaration: public class JTextArea extends JTextComponent

Syntax: JTextArea jta = new JTextArea();

JTextArea Constructors

OO JTextArea(): It is used to create a text area that displays no


text initially.

OO JTextarea(String s): It is used to create a text area that displays


specified text initially.

OO JTextArea(int row, int column): It is used to create a text area


with the specified number of rows and columns that display no
text initially.

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.61
OO JTextarea(String s, int row, int column): It is used to create
a text area with the specified number of rows and columns that
display specified text.

Sample Program to understand the above-discussed Swing


Controls in Java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingDemo2 extends JFrame implements
ActionListener
{
JRadioButton eng, doc;
ButtonGroup bg;
JTextField jtf;
JCheckBox bcd, ccb, acb;
JTextArea jta;
SwingDemo2 ()
{
eng = new JRadioButton ("Engineer");
doc = new JRadioButton ("Doctor");
bg = new ButtonGroup ();
bg.add (eng);
bg.add (doc);
jtf = new JTextField (20);
bcd = new JCheckBox ("Bike");
ccb = new JCheckBox ("Car");
acb = new JCheckBox ("Aeroplane");
jta = new JTextArea (3, 20);
Container c = this.getContentPane ();
c.setLayout (new FlowLayout ());
// Registering the listeners with the
components
eng.addActionListener (this);
doc.addActionListener (this);

M.BALASUBRAMANIAN /AP/HOD OF CS
5.62 Java Programming
bcd.addActionListener (this);
ccb.addActionListener (this);
acb.addActionListener (this);
c.add (eng);
c.add (doc);
c.add (jtf);
c.add (bcd);
c.add (ccb);
c.add (acb);
c.add (jta);
this.setVisible (true);
this.setSize (500, 500);
this.setTitle ("Selection Example");
this.setDefaultCloseOperation (JFrame.
EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae)
{
if (ae.getSource () == eng)
{
jtf.setText ("You are an Engineer");
}
if (ae.getSource () == doc)
{
jtf.setText ("You are an Doctor");
}
String str = " ";
if (bcd.isSelected ())
{
str += "Bike\n";
}
if (ccb.isSelected ())
{
str += "Car\n";

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.63
}
if (acb.isSelected ())
{
str += "Aeroplane\n";
}
jta.setText (str);
}
public static void main (String[]args)
{
new SwingDemo2 ();
}
}
Output

JButton

This component can be used to perform some operations when


the user clicks on it. When the button is pushed, the application results
in some action. It basically inherits the AbstractButton class.

Declaration: public class JButton extends AbstractButton implements


Accessible

Syntax: JButton jb = new JButton();

JButton Constructors

OO JButton(): It is used to create a button with no text and icon.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.64 Java Programming
OO JButton(String s): It is used to create a button with the
specified text.

OO JButton(Icon i): It is used to create a button with the specified


icon object.

Border

The border is an interface using which we can apply a border to


every component. To create the borders we have to use the methods
available in BorderFactory class. We can apply the created border to
any component by using SetBorder() method.

Component.setBorder(Border);

Methods of Border

OO Border createLineBorder(Color, int): It is used to create a


line border. Here, Color object specifies the color of the line
and int specifies the width in pixels of the line.

OO Border createEtchedBorder(int, Color, Color): It is used


to create an etched border. Here, Color arguments specify the
highlight and shadow colors to be used. Here, int arguments
allow the border methods to be specified as either EtchedBorder.
RAISED or EtchedBorder.LOWERED. The methods without
the int arguments create a lowered etched border.

OO Border createBevelBorder(int, Color, Color): It is used to


create a raised or lowered beveled border, specifying the colors
to use. Here, the integer argument can be either BevelBorder.
RAISED or BevelBorder.LOWERED. Here, Color specifies
the highlight and shadow colors.

OO MatteBorder createMatteBorder(int, int, int, int, Icon): It


is used to create a matte border. Here, the integer arguments
specify the number of pixels that the border occupies at the top,
left, bottom, and right (in that order) of whatever component

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.65
uses it. Here, the color argument specifies the color which with
the border should fill its area. Here, the icon argument specifies
the icon which with the border should tile its area.

OO TitledBorder createTitledBorder(Border, String, int, int,


Font, Color): Create a titled border. Here, the string argument
specifies the title to be displayed. Here, the optional font and
color arguments specify the font and color to be used for the
title’s text. Here, the border argument specifies the border
that should be displayed along with the title. Here, the integer
arguments specify the number of pixels that the border occupies
at the top, left, bottom, and right (in that order) of whatever
component uses it.

OO CompoundBorder createCompoundBorder(Border,
Border): Combine two borders into one. Here, the first
argument specifies the outer border; the second, the inner
border.

Sample Program to understand JButton and Border controls in


Swing Java:
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame
{
private JButton button[];
private JPanel panel;
public JButtonDemo ()
{
setTitle ("JButton Borders");
panel = new JPanel ();
panel.setLayout (new GridLayout (7, 1));
button = new JButton[7];
for (int count = 0; count < button.
length; count++)

M.BALASUBRAMANIAN /AP/HOD OF CS
5.66 Java Programming
{
button[count] = new JButton ("Button
" + (count + 1));
panel.add (button[count]);
}
button[0].setBorder (BorderFactory.cre-
ateLineBorder (Color.
blue));
button[1].setBorder (BorderFactory.createBev-
elBorder (0));
button[2].setBorder (BorderFactory.createBev-
elBorder (1, Color.
red, Color.blue));
button[3].setBorder (BorderFactory.createBev-
elBorder (1, Color.
green, Color.orange,Color.red, Color.blue));
button[4].setBorder (BorderFactory.createEmp-
tyBorder (10, 10,
10, 10));
button[5].setBorder (BorderFactory.cre-
ateEtchedBorder (0));
button[6].setBorder (BorderFactory.createTi-
tledBorder ("Titled
Border"));
add (panel, BorderLayout.CENTER);
setSize (400, 300);
setDefaultCloseOperation (JFrame.EXIT_ON_
CLOSE);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[]args)
{
new JButtonDemo ();
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.67
Output

JComboBox

This component will display a group of items as a drop-down


menu from which one item can be selected. At the top of the menu the
choice selected by the user is shown. It basically inherits JComponent
class. We can add the items to the ComboBox by using the addItem()
method.

Example: jcb.addItem(item);

Declaration: public class JComboBox extends JComponent implements


ItemSelectable, ListDataListener, ActionListener, Accessible

Syntax: JComboBox jcb = new JComboBox();

JComboBox Constructors

OO JComboBox(): It is used to create a JComboBox with a default


data model.

OO JComboBox(Object[] items): It is used to create a JComboBox


that contains the elements in the specified array.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.68 Java Programming
OO JComboBox(Vector<?> items): It is used to create a
JComboBox that contains the elements in the specified Vector.

Sample Program to understand JComboBox control in Java


import javax.swing.*;
public class JComboBoxDemo
{
JFrame f;
JComboBoxDemo ()
{
f = new JFrame ("ComboBox Example");
String country[] ={ "Hyderabad", "Chen-
nai", "Bengaluru", "Mumbai", "Delhi" };
JComboBox cb = new JComboBox (country);
cb.setBounds (50, 50, 90, 20);
f.add (cb);
f.setLayout (null);
f.setSize (400, 500);
f.setVisible (true);
}
public static void main (String[]args)
{
new JComboBoxDemo ();
}
}
Output

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.69

JTabbedPane

It is a pane that can contain tabs and each tab can display any
component in the same pane. It is used to switch between a group of
components by clicking on a tab with a given title or icon. To add the
tabs to the JTabbedPane we can use the following methods:

OO jtp.add(TabName, Components)

OO jtp.addTab(TabName, Components)

Declaration: public class JTabbedPane extends JComponent


implements Serializable, Accessible, SwingConstants

Syntax: JTabbedPane jtp = new JTabbedPane();

JTabbedPane Constructors

OO JTabbedPane(): It is used to create an empty TabbedPane.

OO JTabbedPane(int tabPlacement): It is used to create an empty


TabbedPane with a specified tab placement.

M.BALASUBRAMANIAN /AP/HOD OF CS
5.70 Java Programming
OO JTabbedPane(int tabPlacement, int tabLayoutPolicy): It
is used to create an empty TabbedPane with a specified tab
placement and tab layout policy.

Sample Program to understand JTabbedPane control in Java


import javax.swing.*;
import java.awt.*;
public class JTabbedPaneDemo
{
public static void main (String args[])
{
JFrame frame = new JFrame ("Technologies");
JTabbedPane tabbedPane = new JTabbedPane ();
JPanel panel1, panel2, panel3, panel4, panel5;
panel1 = new JPanel ();
panel2 = new JPanel ();
panel3 = new JPanel ();
panel4 = new JPanel ();
panel5 = new JPanel ();
tabbedPane.addTab ("Cricket", panel1);
tabbedPane.addTab ("Badminton ", pan
el2);
tabbedPane.addTab ("Football", panel3);
tabbedPane.addTab ("Basketball ", pan
el4);
tabbedPane.addTab ("Tennis", panel5);
frame.add (tabbedPane);
frame.setDefaultCloseOperation (JFrame.
EXIT_ ON_CLOSE);
frame.setSize (550, 350);
frame.setVisible (true);
}
}

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.71
Output

JPasswordField

It is a text component specialized for password entry. It allows the


editing of a single line of text. It basically inherits the JTextField class.

Declaration: public class JPasswordField extends JTextField

Syntax: JPasswordField jpf = new JPasswordField();

JPasswordFiled Constructors

OO JPasswordField(): It is used to construct a new JPasswordField,


with a default document, null starting text string, and column
width.

OO JPasswordField(int columns): It is used to construct a new


empty JPasswordField with the specified number of columns.

OO JPasswordField(String text): It is used to construct a new


JPasswordField initialized with the specified text.

OO JPasswordField(String text, int columns): It is used to


construct a new JPasswordField initialized with the specified
text and columns.
M.BALASUBRAMANIAN /AP/HOD OF CS
5.72 Java Programming
Sample Program to understand JPasswordFiled Swing control in
Java
import javax.swing.*;
public class JPasswordFieldDemo
{
public static void main (String[]args)
{
JFrame f = new JFrame ("Password Field
Example");
JPasswordField value = new JPassword
Field ();
JLabel l1 = new JLabel ("Password:");
l1.setBounds (20, 100, 80, 30);
value.setBounds (100, 100, 100, 30);
f.add (value);
f.add (l1);
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
}
Output

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.73
QUESTIONS AND ANSWERS

PART-A (2 MARKS)
1. What is an Applet?
An applet is a small Java program that is embedded and ran in
some other Java interpreter program such as
OO a Java technology-enabled browser
OO Sun’s applet viewer program called appletviewer
Applets do not use the main() method for initiating the execution of
the code.
2. Define types of Applet.
OO Applets based on the AWT(Abstract Window Toolkit) package
by extending its Applet class.
OO Applets based on the Swing package by extending its JApplet
class
3. What are all the methods of Applet Class?
OO void init()-The first method to be called when an applet begins
its execution.
OO void start()- Called automatically after init() method to start the
execution of an applet.
OO void paint(): The paint() method belongs to the Graphics class
in Java. It is used to draw shapes like circle, square, trapezium,
etc., in the applet.
4. Write syntax for entire Applet Lifecycle.
class TestAppletLifeCycle extends Applet
{
public void init()
{

M.BALASUBRAMANIAN /AP/HOD OF CS
5.74 Java Programming
// initialized objects
}
public void start()
{
// code to start the applet
}
public void paint(Graphics graphics)
{
// draw the shapes
}
public void stop()
{
// code to stop the applet
}
public void destroy()
{
// code to destroy the applet
}
}
5. How to pass the parameters in Applet?
OO To pass the parameters to the Applet we need to use the param
attribute of <applet> tag.
OO To retrieve a parameter's value, we need to use the getParameter()
method of Applet class.
void stop() Called when an applet has to pause/stop its
execution.
void destoy() Called when an appLet us finally terminated.
6. Write any two Graphics class in Java.
java.awt.Graphics class provides many methods for graphics

M.BALASUBRAMANIAN /AP/HOD OF CS
Working with APPLETS, AWT and Swings 5.75
programming. Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used
to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
7. What is Event Handling?
An event in a java program is generated upon clicking a button,
typing in a textfield, checking a checkbox or radio box, selecting an
item in a drop down list etc
To listen events, we must implement interfaces related to the
kind of event that is generated by our program. For example, if our
program has a button in it and in order to listen a button click event, we
must implement ActionListener interface and implement its method
actionPerformed(), which gives us the name of the button that was
clicked, that lead to a button click event.
8. What is a GUI?
GUI (Graphical User Interface) in Java is an easy-to-use visual
experience builder for Java applications. It is mainly made of graphical
components like buttons, labels, windows, etc. through which the user
can interact with an application. GUI plays an important role to build
easy interfaces for Java applications.
9. How to create Dialogue boxes in GUI applications?
The JOptionPane class is used to provide standard dialog boxes
such as message dialog box, confirm dialog box and input dialog box.
These dialog boxes are used to display information or get input from
the user. The JOptionPane class inherits JComponent class.
10. Write any three` layout managers in GUI application.
FlowLayout
BorderLayout
GridLayout

M.BALASUBRAMANIAN /AP/HOD OF CS
5.76 Java Programming
REVIEW QUESTIONS
PART - B (5 MARKS)
1. Give a detailed information about Applet Class.

2. Write a steps for developing an applet program.

3. Write short notes on Event handling in applet.

4. Discuss on dialogue boxex in applet.

5. List all the layout managers used in IDE.

PART - C (10 MARKS)


1. Draw a neat diagram of Applet life cycle and explain briefly.

2. List all the Graphics methods used in applet.

3. Explain – AWT Component class

4. Explain – Swing Component class

5. Discuss the difference between AWT and Swing concepts in


java.

M.BALASUBRAMANIAN /AP/HOD OF CS

You might also like