0% found this document useful (0 votes)
33 views325 pages

Oop Java Unit 5

Uploaded by

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

Oop Java Unit 5

Uploaded by

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

Java™:

The Complete Reference


UNIT – 4 & Chapter – 13

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• Applet: Basics, Architecture, Applet Skeleton,
requesting repainting, using the status window,
passing parameters to applets

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Applets
• All of the preceding examples have been Java console-based
applications.
• However, these types of applications constitute only one class of
Java programs. Another type of program is the applet.
• Applets are small applications that are accessed on an Internet
server, transported over the Internet, automatically installed,
and run as part of a web document.
• After an applet arrives on the client, it has limited access to
resources so that it can produce a graphical user interface and
run complex computations without introducing the risk of
viruses or breaching data integrity.
• An applet is a Java program that can be embedded into a web
page. It runs inside the web browser and works at client side. An
applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.
• Applets are used to make the web site more dynamic and
entertaining.
Applets
• Advantage of Applet
– It works at client side so less response time.
– Secured
– It can be executed by browsers running under many
platforms, including Linux, Windows, Mac Os etc.
• Drawback of Applet
– Plugin is required at client browser to execute applet.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
• This applet begins with two import statements.
import java.awt.*;
import java.applet.*;
• The first imports the Abstract Window Toolkit
(AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT, not
through the console-based I/O classes. The AWT
contains support for a window-based, graphical
user interface.
• The second import statement imports the applet
package, which contains the class Applet. Every
applet that you create must be a subclass of
Applet.
paint()
• paint( ) method is defined by the AWT and must be
overridden by the applet.
• paint( ) is called each time that the applet must
redisplay its output.
• paint( ) is also called when the applet begins
execution.
• Whenever the applet must redraw its output, paint( )
is called.
• The paint( ) method has one parameter of type
Graphics. This parameter contains the graphics
context, which describes the graphics environment in
which the applet is running. This context is used
whenever output to the applet is required.
drawString()
• Inside paint( ) is a call to drawString( ), which is a
member of the Graphics class. This method outputs a
string beginning at the specified X,Y location.
void drawString(String message, int x, int y)
• Here, message is the string to be output beginning at
x,y.
• In a Java window, the upper-left corner is location 0,0.
• applet does not have a main( ) method.
• An applet begins execution when the name of its class
is passed to an applet viewer or to a network browser.
Run an applet
• Compile in the same way that you have been compiling
programs.
• There are two ways in which you can run an applet:
– Executing the applet within a Java-compatible web browser.
To execute an applet in a web browser, you need to write a short
HTML text file that contains a tag that loads the applet. Currently, Sun
recommends using the APPLET tag for this purpose.
<applet code="SimpleApplet" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used
by the applet.
– Using an applet viewer, such as the standard tool, appletviewer. An
applet viewer executes your applet in a window. This is generally the
fastest and easiest way to test your applet.
To execute SimpleApplet with an applet viewer, you may also execute
the HTML file. For example, if the preceding HTML file is called
RunApp.html, then the following command line will run SimpleApplet:
C:\>appletviewer RunApp.html
• However, a more convenient method exists that
you can use to speed up testing.
• Simply include a comment at the head of your
Java source code file that contains the APPLET tag.
• By doing so, your code is documented with a
prototype of the necessary HTML statements, and
you can test your compiled applet merely by
starting the applet viewer with your Java source
code file.
//SimpleApplet.java using appletviewer
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
//SimpleApplet.java using web browser
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}

applet1.html
<html>
<applet code="SimpleApplet" width=200 height=60>
</applet>
</html>
Syntax of Applet tag in HTML
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>] [<
PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
Life cycle of an applet
• Applet is initialized.
– public void init(): is used to initialized the
Applet. It is invoked only once.
• Applet is started.
– public void start(): is invoked after the init()
method or browser is maximized. It is used to
start the Applet.
• Applet is painted.
– public void paint(Graphics g): is used to paint
the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
• Applet is stopped.
– public void stop(): is used to stop the Applet. It
is invoked when Applet is stop or browser is
minimized.
• Applet is destroyed.
– public void destroy(): is used to destroy the
Applet. It is invoked only once.
Life cycle of an applet
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletLifeCycle" width=200 height=60>
</applet>
*/
public class AppletLifeCycle extends Applet
{
public void init()
{
setBackground(Color.CYAN);
System.out.println("init() called");
}
public void start()
{
System.out.println("Start() called");
}
public void paint(Graphics g)
{
System.out.println("Paint() called");
}
public void stop()
{
System.out.println("Stop() Called");
}
public void destroy()
{
System.out.println("Destroy() Called");
}
}
showStatus(String msg)
In addition to displaying information in its window, an
applet can also output a message to the status window
of the browser or applet viewer on which it is running.
To do so, call showStatus( ) with the string that you want
displayed.
The status window is a good place to give the user
feedback about what is occurring in the applet, suggest
options, or possibly report some types of errors.
The status window also makes an excellent debugging
aid, because it gives you an easy way to output
information about your applet.
showStatus(String msg)

public void paint(Graphics g) {


g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
Parameters passed to an applet
• To pass the parameters to the Applet we need to
use the param attribute of <applet> tag.
• To retrieve a parameter's value, we need to use
the getParameter() method of Applet class.
public String getParameter(String name)
• Method takes a String argument name, which
represents the name of the parameter which was
specified with the param attribute in the <applet>
tag.
• Method returns the value of the name parameter(if
it was defined) else null is returned.
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet8" width="400" height="200">
<param name="Name" value="Mahesh">
<html>
<param name="College" value="RECW">
<applet code="Applet8" width="400"
<param name="Branch" value="CSE">
height="200">
<param name="Sport" value="Tennis">
<param name="Name" value="Mahesh">
</applet>
<param name="College" value="RECW">
*/
<param name="Branch" value="CSE">
public class Applet8 extends Applet
<param name="Sport" value="Tennis">
{
</applet>
String name;
</html>
String college;
String sport;
String branch;

public void init()


{
name = getParameter("Name");
college = getParameter("College");
branch = getParameter("Branch");
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("College -" + college, 20, 60);
g.drawString("Branch -" + branch, 20, 80);
g.drawString("Favorite sport -" + sport, 20, 100);
}
}
END
Java™:
The Complete Reference
UNIT – 5 & Chapter – 29

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• GUI Programming with Swings – The origin and
design philosophy of swing, components and
containers, layout managers, event handling, using
a push button, jtextfield, jlabel and image icon,
the swing buttons, jtext field, jscrollpane, jlist,
jcombobox, trees, jtable, An overview of
jmenubar, jmenu and jmenuitem, creating a main
menu, showmessagedialog, showconfirmdialog,
showinputdialog, showoptiondialog, jdialog,
create a modeless dialog.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
AWT (Abstract Window Toolkit)
• 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 AWT contains numerous classes and methods that allow you to
create and manage windows.
• A common use of the AWT is in applets, it is also used to create stand-
alone windows that run in a GUI environment, such as Windows.
• To run applets, you need to use an appletviewer or a Java-compatible web
browser.
• Today, most Java programs employ user interfaces based on Swing.
Because Swing provides richer implementations than does the AWT of
some common GUI controls, such as buttons, lists, and check boxes.
• Swing is built on top of the AWT, many AWT classes are used either
directly or indirectly by Swing.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Difference between AWT and Swing

No. Java AWT Java Swing


1) AWT components are platform- Java swing components
dependent. are platform-independent.
2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable Swing supports pluggable look and


look and feel. feel.
4) AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5) AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.
Java Foundation Classes (JFC)
• Swing in Java is a Graphical User Interface (GUI) toolkit that
includes the GUI components. Swing provides a rich set of
widgets and packages to make sophisticated GUI
components for Java applications. Swing is a part of Java
Foundation Classes(JFC), which is an API for Java programs
that provide GUI.
• The Java Swing library is built on top of the Java Abstract
Widget Toolkit (AWT), an older, platform dependent GUI
toolkit. You can use the Java GUI programming components
like button, textbox, etc. from the library and do not have to
create the components from scratch.
• The Java Foundation Classes (JFC) are a set of GUI
components which simplify the development of desktop
applications.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Hierarchy of Java Swing classes
All components in Java
Swing are JComponent
which can be added to
container classes.
Components and Containers
• A Swing GUI consists of two key items: components and
containers.
• The difference between the two is found in their intended
purpose: As the term is commonly used, a component is an
independent visual control, such as a push button or slider.
• A container holds a group of components. Thus, a container
is a special type of component that is designed to hold
other components.
• Furthermore, in order for a component to be displayed, it
must be held within a container. Thus, all Swing GUIs will
have at least one container. Because containers are
components, a container can also hold other containers.
• This enables Swing to define what is called a containment
hierarchy, at the top of which must be a top-level container.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Container
• Swing defines two types of containers.
1. The first are top-level containers: JFrame, Japplet,
JWindow, and JDialog.
– These containers do not inherit JComponent. They do,
however, inherit the AWT classes Component and
Container. The top-level containers are heavyweight.
– The one most commonly used for applications is
JFrame. The one used for applets is JApplet.
2. The second type of containers supported by Swing are
lightweight containers. Lightweight containers do
inherit JComponent. An example of a lightweight
container is JPanel, which is a general-purpose
container.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
JComponent class
• The JComponent class is the base class of all Swing
components except top-level containers.
• Swing components whose names begin with "J" are
descendants of the JComponent class. For example,
JButton, JScrollPane, JPanel, JTable etc.
• But, JFrame and JDialog don't inherit JComponent
class because they are the child of top-level
containers.
• The JComponent class extends the Container class
which itself extends Component. The Container class
has support for adding components to the container.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame(); //creating instance of JFrame

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
}
}
Model-View-Controller (MVC)
• A visual component is a composite of three
distinct aspects:
– The way that the component looks when rendered on
the screen
– The way that the component reacts to the user
– The state information associated with the component
• No matter what architecture is used to implement
a component, it must implicitly contain these
three parts. Over the years, one component
architecture has proven itself to be exceptionally
effective: Model-View-Controller, or MVC for short.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Model-View-Controller (MVC)
• The MVC architecture is successful because each piece of
the design corresponds to an aspect of a component.
• In MVC terminology, the model corresponds to the state
information associated with the component. For example, in
the case of a check box, the model contains a field that
indicates if the box is checked or unchecked.
• The view determines how the component is displayed on
the screen, including any aspects of the view that are
affected by the current state of the model.
• The controller determines how the component reacts to the
user. For example, when the user clicks a check box, the
controller reacts by changing the model to reflect the user’s
choice (checked or unchecked).

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Model-View-Controller (MVC)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
The Swing Packages

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
JLabel
Constructor Description

JLabel() Creates a JLabel instance with no


image and with an empty string for
the title.

JLabel(String s) Creates a JLabel instance with the


specified text.

JLabel(Icon i) Creates a JLabel instance with the


specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the


horizontalAlignment) specified text, image, and horizontal
alignment.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
JLabel
Methods Description

String getText() t returns the text string that a


label displays.

void setText(String text) It defines the single line of text


this component will display.

void It sets the alignment of the label's


setHorizontalAlignment(int contents along the X axis.
alignment)
Icon getIcon() It returns the graphic image that
the label displays.

int getHorizontalAlignment() It returns the alignment of the


label's contents along the X axis.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample1 extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample1(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample1();
}}
import javax.swing.*;
class LabelDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
ImageIcon i = new ImageIcon("D:/Penguins.jpg");

l2=new JLabel(i);
l2.setBounds(50,100, 300,100);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JButton
public class JButton extends AbstractButton implements Accessible

Constructor Description

JButton() It creates a button with no


text and icon.

JButton(String s) It creates a button with the


specified text.

JButton(Icon i) It creates a button with the


specified icon object.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
JButton
Methods Description
void setText(String s) It is used to set specified text on
button
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable the
button.
void setIcon(Icon b) It is used to set the specified Icon
on the button.

Icon getIcon() It is used to get the Icon of the


button.
void setMnemonic(int a) It is used to set the mnemonic on
the button.
void It is used to add the action
addActionListener(ActionListener a) listener to this object.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating 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 managers
f.setVisible(true);//making the frame visible
}

public static void main(String[] args) {


new Simple();
}
}
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
JButton
import javax.swing.*;
public class Simple2 extends JFrame{ //inheriting 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();
}}

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
What is an Event
• Change in the state of an object is known as Event, i.e., event
describes the change in the state of the source.
• Events are generated as a 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 the list, and
scrolling the page are the activities that causes an event to occur.
• The events can be broadly classified into two categories −
– Foreground Events − These events require direct interaction of the
user. They are generated as consequences of a person interacting with
the graphical components in the 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 − These events require the interaction of the end
user. Operating system interrupts, hardware or software failure, timer
expiration, and operation completion are some examples of
background events.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Event Handling
• Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs.
• This mechanism has a code which is known as an 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.
• The Delegation Event Model has the following key participants.
– Source − The source is an object on which the event occurs. Source is
responsible for providing information of the occurred event to it's
handler. Java provide us with classes for the source object.
– Listener − It is also known as event handler. The listener is responsible
for generating a response to an event. From the point of view of Java
implementation, the listener is also an object. The listener waits till it
receives an event. Once the event is received, the listener processes
the event and then returns.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Steps Involved in Event Handling
• Step 1 − The user clicks the button and the event is
generated.
• Step 2 − The object of concerned event class is created
automatically and information about the source and the
event get populated within the same object.
• Step 3 − Event object is forwarded to the method of the
registered listener class.
• Step 4 − The method is gets executed and returns.
• 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 represent an event method. In
response to an event, java jre will fire callback method. All
such callback methods are provided in listener interfaces.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to RECW.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.

public class JTextField extends JTextComponent implements SwingConstants

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized


with the specified text.

JTextField(String text, int columns) Creates a new TextField initialized


with the specified text and columns.

JTextField(int columns) Creates a new empty TextField with


the specified number of columns.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
JTextField
Methods Description

void addActionListener(ActionListener l) It is used to add the specified action


listener to receive action events from
this textfield.
Action getAction() It returns the currently set Action for
this ActionEvent source, or null if no
Action is set.
void setFont(Font f) It is used to set the current font.

void removeActionListener(ActionListener l) It is used to remove the specified


action listener so that it no longer
receives action events from this
textfield.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import javax.swing.*; Example-1
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to RECW.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
import javax.swing.*; Example-2
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);

b1.addActionListener(this);
b2.addActionListener(this);

f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}
}
JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class

public class JTextArea extends JTextComponent

Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text
initially.
JTextArea(int row, int column) Creates a text area with the specified number of
rows and columns that displays no text initially.
JTextArea(String s, int row, int column) Creates a text area with the specified number of
rows and columns that displays specified text.

Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of
columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified text on the
specified position.
void append(String s) It is used to append the given text to the
end of the document.
import javax.swing.*; Example-1
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to Ravindra College of Engineering”);
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
import javax.swing.*; Example-2
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
JPasswordField
The object of a JPasswordField class is a text component specialized for password
entry. It allows the editing of a single line of text. It inherits JTextField class.

public class JPasswordField extends JTextField

import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
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);
}
}
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.

public class JCheckBox extends JToggleButton implements Accessible


Constructor Description
JJCheckBox() Creates an initially unselected check box
button with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with
text.
JCheckBox(String text, boolean selected) Creates a check box with text and specifies
whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are
taken from the Action supplied.

Methods Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.
protected String paramString() It returns a string representation of this
JCheckBox.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
JCheckBox

checkbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JCheckBox cb = (JCheckBox) event.getSource();
if (cb.isSelected()) {
// do something if check box is selected
} else {
// check box is unselected, do something else
}
}
});
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.

public class JRadioButton extends JToggleButton implements Accessible

Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean selected) Creates a radio button with the specified text and
selected status.

Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
import javax.swing.*; Example-1
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
import javax.swing.*; Example-2
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{

JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits JComponent class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,


ActionListener, Accessible
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the
specified Vector.

Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the
list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};

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 ComboBoxExample();
}
}
JList
The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.

public class JList extends JComponent implements Scrollable, Accessible

Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the
specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the
specified, non-null, model.

Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener(ListSelectionListen notified each time a change to the selection
er listener) occurs.
int getSelectedIndex() It is used to return the smallest selected cell
index.
ListModel getModel() It is used to return the data model that holds a
list of items displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from
an array of objects.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.

Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified data.
columns)
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java™:
The Complete Reference
UNIT – 5 & Chapter – 29

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• GUI Programming with Swings – The origin and
design philosophy of swing, components and
containers, layout managers, event handling, using
a push button, jtextfield, jlabel and image icon,
the swing buttons, jtext field, jscrollpane, jlist,
jcombobox, trees, jtable, An overview of
jmenubar, jmenu and jmenuitem, creating a main
menu, showmessagedialog, showconfirmdialog,
showinputdialog, showoptiondialog, jdialog,
create a modeless dialog.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
JTree
The JTree class is used to display the tree structured data or hierarchical data.
JTree is a complex component. It has a 'root node' at the top most which is a parent for all
nodes in the tree. It inherits JComponent class.

public class JTree extends JComponent implements Scrollable, Accessible

Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] value) Creates a JTree with every element of the
specified array as the child of a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as
its root, which displays the root node.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
JMenuBar
The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.
The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.

JMenuBar class declaration


public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration


public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration


public class JMenuItem extends AbstractButton implements Accessible, MenuElement
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new MenuExample();
}}
import java.awt.event.*; Creating menu for Notepad
public class MenuExample implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample();
}
}
JOptionPane
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.

public class JOptionPane extends JComponent implements Accessible


Methods Description
JDialog createDialog(String title) It is used to create and return a new
parentless JDialog with the specified title.
static void showMessageDialog(Component It is used to create an information-message
parentComponent, Object message) dialog titled "Message".
static void showMessageDialog(Component It is used to create a message dialog with
parentComponent, Object message, String given title and messageType.
title, int messageType)
static int showConfirmDialog(Component It is used to create a dialog with the options
parentComponent, Object message) Yes, No and Cancel; with the title, Select an
Option.
static String showInputDialog(Component It is used to show a question-message dialog
parentComponent, Object message) requesting input from the user parented to
parentComponent.
void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.
showMessageDialog()
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Welcome to RECW.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
showMessageDialog()
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.
WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
showInputDialog()
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
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) {
int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}}
Jdialog class
The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.

public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneCont


ainer

Constructor Description
JDialog() It is used to create a modeless dialog
without a title and without a specified
Frame owner.
JDialog(Frame owner) It is used to create a modeless dialog
with specified Frame as its owner and an
empty title.
JDialog(Frame owner, String title, It is used to create a dialog with the
boolean modal) specified title, owner Frame and modality.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
} }
LayoutManager
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
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);
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.
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));//creating grid layout of 3 row and 3 columns


f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();}}
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.
import java.awt.*;
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();}}
BoxLayout
The BoxLayout is used to arrange the components
either vertically or horizontally. For this purpose,
BoxLayout provides four constants. They are as follows:

Fields of BoxLayout class


1.public static final int X_AXIS
2.public static final int Y_AXIS
3.public static final int LINE_AXIS
4.public static final int PAGE_AXIS
Constructor of BoxLayout class
1.BoxLayout(Container c, int axis): creates a box
layout that arranges the components with the given
axis.

Note: BoxLayout class is found in javax.swing package.


//Example of BoxLayout class with Y-AXIS
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame {


Button buttons[];

public BoxLayoutExample1 () {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}

setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));


setSize(400,400);
setVisible(true);
}

public static void main(String args[]){


BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
// Example of BoxLayout class with X-AXIS
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample2 extends Frame {


Button buttons[];

public BoxLayoutExample2() {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}

setLayout (new BoxLayout(this, BoxLayout.X_AXIS));


setSize(400,400);
setVisible(true);
}

public static void main(String args[]){


BoxLayoutExample2 b=new BoxLayoutExample2();
}
}
CardLayout
The CardLayout class manages the components in such a manner
that only one component is visible at a time. It treats each
component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
1.CardLayout(): creates a card layout with zero horizontal and
vertical gap.
2.CardLayout(int hgap, int vgap): creates a card layout with
the given horizontal and vertical gap.
Commonly used methods of CardLayout class
•public void next(Container parent): is used to flip to the next
card of the given container.
•public void previous(Container parent): is used to flip to the
previous card of the given container.
•public void first(Container parent): is used to flip to the first
card of the given container.
•public void last(Container parent): is used to flip to the last
card of the given container.
•public void show(Container parent, String name): is used to
flip to the specified card with the given name.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutExample extends JFrame implements ActionListener{


CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){

c=getContentPane();
card=new CardLayout(40,30); //cardLayout object with 40 hor and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

c.add("a",b1);c.add("b",b2);c.add("c",b3);

}
public void actionPerformed(ActionEvent e) {
card.next(c);
}

public static void main(String[] args) {


CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
GridBagLayout
The Java GridBagLayout class is used to align components
vertically, horizontally or along their baseline.
The components may not be of same size.
Each GridBagLayout object maintains a dynamic, rectangular grid
of cells.
Each component occupies one or more cells known as its display
area. Each component associates an instance of
GridBagConstraints. With the help of constraints object we arrange
component's display area on the grid. The GridBagLayout manages
each component's minimum and preferred sizes in order to
determine component's size.
import java.awt.*;
class GridBagLayoutExample extends Frame {
GridBagLayoutExample() {
Label lblName = new Label("Name");
TextField txtName =new TextField(10);
Label lblcomments = new Label("Comments");
TextArea TAreaComments=new TextArea(6,15);
Button btnSubmit = new Button("Submit");
setLayout(new GridBagLayout());
GridBagConstraints gc =new GridBagConstraints();
add(lblName,gc,0,0,1,1,0,0);
add(txtName,gc,1,0,1,1,0,20);
add(lblcomments,gc,0,1,1,1,0,0);
add(TAreaComments,gc,1,1,1,1,0,60);
add(btnSubmit,gc,0,2,2,1,0,20);
}
void add(Component comp,GridBagConstraints gc,int x,int y,int w,int h,int wx,int wy) {
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = w;
gc.gridheight= h;
gc.weightx = wx;
gc.weighty = wy;
add(comp,gc);
} }
class GridBagLayoutJavaExample
{
public static void main(String args[])
{
GridBagLayoutExample frame = new GridBagLayoutExample();
frame.setTitle("GridBagLayout in Java Example");
frame.setSize(300,200);
frame.setVisible(true);
}
}
Java™:
The Complete Reference
UNIT – 5 & Chapter – 24

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• Introduction the AWT: Working with windows,
graphics and Text AWT classes, window fundamentals
working with frame windows creating a frame
window in a an AWT Based applet creating a window
program displaying information within a window
Graphics working with color and fonts setting the
paint mode managing text output using font metrics
• Using AWT controls, Layout Mangers, and Menus
AWT control fundamentals Labels, using buttons
applying check boxes, check box group choice
controls, using lists Managing scroll bars using a Text
field, Using a Text area understanding layout
managers Menu bars and Menus dialog boxes, file
RCEW, Pasupula (V), Nandikotkur Road,
dialog Overriding paint() Near Venkayapalli, KURNOOL
Controls
• The AWT supports the following types of controls:
– Labels
– Push buttons
– Check boxes
– Choice lists
– Lists
– Scroll bars
– Text editing

These controls are subclasses of Component.


RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Adding and Removing Controls
• To include a control in a window, you must add it to
the window.
• To do this, you must first create an instance of the
desired control and then add it to a window by calling
add( ), which is defined by Container.
• The add( ) method has several forms.
Component add(Component compObj)
• Here, compObj is an instance of the control that you
want to add. A reference to compObj is returned.
• Once a control has been added, it will automatically
be visible whenever its parent
RCEW, window
Pasupula is displayed.
(V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Adding and Removing Controls
• To remove a control from a window when the
control is no longer needed. To do this, call
remove( ).
void remove(Component obj)
• Here, obj is a reference to the control
• Remove all controls by calling removeAll( ).

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Responding to Controls
• Except for labels, which are passive, all controls
generate events when they are accessed by the
user.
• For example, when the user clicks on a push
button, an event is sent that identifies the push
button.
• In general, program simply implements the
appropriate interface and then registers an event
listener for each control.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
The HeadlessException
• Most of the AWT controls have constructors that
can throw a HeadlessException when an attempt
is made to instantiate a GUI component in a non-
interactive environment (such as one in which no
display, mouse, or keyboard is present).
• The HeadlessException was added by Java 1.4.
• Use this exception to write code that can adapt to
non-interactive environments.
• This exception is not handled by the programs.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Labels
• A label is an object of type Label, and it contains a
string, which it displays. Labels are passive controls
that do not support any interaction with the user.
Label( ) throws HeadlessException
creates a blank label.
Label(String str) throws HeadlessException
creates a label that contains the string specified
by str. This string is left-justified.
Label(String str, int how) throws HeadlessException
creates a label that contains the string specified
by str using the alignment specified by how. The
value of how must be one of these three
constants: Label.LEFT, Label.RIGHT, or Label.CENTER.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Labels
• To set or change the text in a label by using the
setText( ) method.
void setText(String str)
str specifies the new label.
• To obtain the current label by calling getText( ).
String getText( )
• set the alignment of the string within the label by
calling setAlignment( ).
void setAlignment(int how)
• To obtain the current alignment, getAlignment( ).
int getAlignment( ) Pasupula (V), Nandikotkur Road,
RCEW,
Near Venkayapalli, KURNOOL
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/* <applet code="LabelDemo" width=300 height=200>
</applet> */
public class LabelDemo extends Applet {
public void init() {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}
Buttons
• Most widely used control is the push button. A push
button is a component that contains a label and that
generates an event when it is pressed.
• Push buttons are objects of type Button.
• Button defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
• The first version creates an empty button. The second
creates a button that contains str as a label.
• To set and get label using
void setLabel(String str)
String getLabel( )RCEW,Near
Pasupula (V), Nandikotkur Road,
Venkayapalli, KURNOOL
Handling Buttons
• Each time a button is pressed, an action event is generated.
• This is sent to any listeners that previously registered an
interest in receiving action event notifications from that
component.
• Each listener implements the ActionListener interface. That
interface defines the actionPerformed( ) method, which is
called when an event occurs.
• An ActionEvent object is supplied as the argument to this
method. It contains both a reference to the button that
generated the event and a reference to the action
command string associated with the button.
• By default, the action command string is the label of the
button. Usually, either the button reference or the action
command string can beRCEW,usedPasupula
to identify the button.
(V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="ButtonDemo" width=250 height=150>
</applet>*/

public class ButtonDemo extends Applet implements ActionListener {


String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}
getSource( ) method
• getSource( ) method to the button objects that you added
to the window.
• To do this, you must keep a list of the objects when they are
added.

Button bList[] = new Button[3];


public void init() {
public void actionPerformed(ActionEvent ae) {
Button yes = new Button("Yes");
for(int i = 0; i < 3; i++) {
Button no = new Button("No");
if(ae.getSource() == bList[i]) {
Button maybe = new Button("Undecided");
msg = "You pressed " + bList[i].getLabel();
// store references to buttons as added
}
bList[0] = (Button) add(yes);
}
bList[1] = (Button) add(no);
repaint();
bList[2] = (Button) add(maybe);
}
// register to receive action events
for(int i = 0; i < 3; i++) {
bList[i].addActionListener(this);
} RCEW, Pasupula (V), Nandikotkur Road,
} Near Venkayapalli, KURNOOL
TextField
• The TextField class implements a single-line text-entry area,
usually called an edit control.
• Text fields allow the user to enter strings and to edit the text
using the arrow keys, cut and paste keys, and mouse
selections.
• TextField is a subclass of TextComponent.
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
• The first version creates a default text field.
• The second form creates a text field that is numChars
characters wide.
• The third form initializes the text field with the string
contained in str.
RCEW,
• The fourth form initializes Pasupula
aNear
text field (V),
and Nandikotkur
sets its Road,
width.
Venkayapalli, KURNOOL
TextField
• To obtain the string currently contained in the text field, call
getText( ).
• To set the text, call setText( ).
String getText( )
void setText(String str)
Here, str is the new string.
• The user can select a portion of the text in a text field.
String getSelectedText( )
• getSelectedText( ) returns the selected text.
• Also, you can select a portion of text under program control
by using select( ).
void select(int startIndex, int endIndex)
• The select( ) method selects the characters beginning at
startIndex and ending at endIndex–1.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
TextField
boolean isEditable( )
void setEditable(boolean canEdit)
• isEditable( ) returns true if the text may be changed
and false if not.
• In setEditable( ), if canEdit is true, the text may be
changed. If it is false, the text cannot be altered.
• There may be times when you will want the user to
enter text that is not displayed, such as a password.
You can disable the echoing of the characters as they
are typed by calling setEchoChar( ).
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
• Here, ch specifies the character to be echoed.
Handling a TextField

Program generally will not respond to individual key


events that occur within a text field.

However, you may want to respond when the user presses


ENTER.
//Sample Login Page using applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyLoginPage" width=300 height=300>
</applet>
*/
public class MyLoginPage extends Applet implements ActionListener
{
TextField name,pass;
Button b1,b2;
public void init()
{
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('*');
b1=new Button("submit");
b2=new Button("cancel");
add(n);
add(name);
add(p);
add(pass);
add(b1);
add(b2);
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(280,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g)
{
g.drawString("Name: " + name.getText(), 6, 100);
g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 130);
g.drawString("Password: " + pass.getText(), 6, 160);
}
}
Check Boxes
• A check box is a control that is used to turn an option
on or off.
• It consists of a small box that can either contain a
check mark or not.
• There is a label associated with each check box that
describes what option the box represents.
• You change the state of a check box by clicking on it.
• Check boxes can be used individually or as part of a
group.
Checkbox( ) throws HeadlessException
Checkbox(String str) throws HeadlessException
Checkbox(String str, boolean on) throws HeadlessException
Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
RCEW,
Checkbox(String str, CheckboxGroup Pasupula
cbGroup, (V),throws
boolean on) Nandikotkur Road,
HeadlessExceptionp
Near Venkayapalli, KURNOOL
Check Boxes
• To retrieve the current state of a check box, call
getState().
• To set its state, call setState( ).
• To obtain the current label associated with a check box by
calling getLabel( ).
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Handling Check Boxes
• Each time a check box is selected or deselected, an
item event is generated.
• This is sent to any listeners that previously
registered an interest in receiving item event
notifications from that component. Each listener
implements the ItemListener interface. That
interface defines the itemStateChanged( ) method.
• An ItemEvent object is supplied as the argument
to this method. It contains information about the
event.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="CheckboxDemo" width=250 height=200>
</applet> */

public class CheckboxDemo extends Applet implements ItemListener {


String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init() {
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
CheckboxGroup
• It is possible to create a set of mutually exclusive
check boxes in which one and only one check box in
the group can be checked at any one time.
• These check boxes are often called radio buttons,
because they act like the station selector on a car
radio—only one station can be selected at any one
time.
• To create a set of mutually exclusive check boxes, you
must first define the group to which they will belong
and then specify that group when you construct the
check boxes.
• Check box groups areRCEW, Pasupula (V), Nandikotkur Road,
objects of type CheckboxGroup.
Near Venkayapalli, KURNOOL
CheckboxGroup
• To determine which check box in a group is
currently selected by calling
getSelectedCheckbox().
Checkbox getSelectedCheckbox( )
• You can set a check box by calling
setSelectedCheckbox( ).
void setSelectedCheckbox(Checkbox which)
• Here, which is the check box that you want to be
selected.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Demonstrate check box group.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="CBGroup" width=250 height=200> </applet> */
public class CBGroup extends Applet implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
winXP = new Checkbox("Windows XP", cbg, true);
winVista = new Checkbox("Windows Vista", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("Mac OS", cbg, false);
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
Choice Controls
• The Choice class is used to create a pop-up list of
items from which the user may choose.
• Thus, a Choice control is a form of menu. When
inactive, a Choice component takes up only enough
space to show the currently selected item. When the
user clicks on it, the whole list of choices pops up, and
a new selection can be made. Each item in the list is a
string that appears as a left-justified label in the order
it is added to the Choice object.
• Choice only defines the default constructor, which
creates an empty list.
• To add a selection to the list, call add( ).
void add(String name)
• Here, name is the name ofPasupula
RCEW, the item(V), being added.
Nandikotkur Road,
Near Venkayapalli, KURNOOL
Choice Controls
• To determine which item is currently selected, you may call either
getSelectedItem( ) or getSelectedIndex( ).
String getSelectedItem( )
int getSelectedIndex( )
• The first item is at index 0. By default, the first item added to the list is
selected.
• To obtain the number of items in the list, call getItemCount().
• You can set the currently selected item using the select( ) method with
either a zero-based integer index or a string that will match a name in the
list.
int getItemCount( )
void select(int index)
void select(String name)
• you can obtain the name associated with the item at that index by calling
getItem( )
String getItem(int index)
• Here, index specifies the index of the desired item.
Handling Choice Lists
• Each time a choice is selected, an item event is
generated.
• This is sent to any listeners that previously registered
an interest in receiving item event notifications from
that component.
• Each listener implements the ItemListener interface.
• That interface defines the itemStateChanged( )
method.
• An ItemEvent object is supplied as the argument to
this method.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
// Demonstrate Choice lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ChoiceDemo" width=300 height=180></applet>*/

public class ChoiceDemo extends Applet implements ItemListener {


Choice os, browser;
String msg = "";
public void init() {
os = new Choice();
browser = new Choice();
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
// add choice lists to window
add(os);
add(browser);
// register to receive item events
os.addItemListener(this);
browser.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Using Lists
• The List class provides a compact, multiple-choice,
scrolling selection list. Unlike the Choice object,
which shows only the single selected item in the
menu, a List object can be constructed to show
any number of choices in the visible window. It
can also be created to allow multiple selections.
List( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws
HeadlessException

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
• The first version creates a List control that allows only one
item to be selected at any one time.
• In the second form, the value of numRows specifies the
number of entries in the list that will always be visible
(others can be scrolled into view as needed).
• In the third form, if multipleSelect is true, then the user may
select two or more items at a time. If it is false, then only
one item may be selected.
• To add a selection to the list, call add( ). It has the following
two forms:
void add(String name)
void add(String name, int index)
• Here, name is the name of the item added to the list.
• The first form adds items to the end of the list.
• The second form adds the item at the index specified by
index. Indexing begins at zero. You can specify –1 to add the
item to the end of the list.
• For lists that allow only single selection, you can
determine which item is currently selected by calling
either getSelectedItem( ) or getSelectedIndex( ).
String getSelectedItem( )
int getSelectedIndex( )
• The getSelectedItem( ) method returns a string
containing the name of the item.
• If more than one item is selected, or if no selection
has yet been made, null is returned.
• getSelectedIndex( ) returns the index of the item. The
first item is at index 0. If more than one item is
selected, or if no selection has yet been made, –1 is
returned.
• For lists that allow multiple selection, you must use either
getSelectedItems( ) or getSelectedIndexes( ), shown here, to
determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
• getSelectedItems( ) returns an array containing the names of the
currently selected items.
• getSelectedIndexes( ) returns an array containing the indexes of
the currently selected items.
• To obtain the number of items in the list, call getItemCount( ).
You can set the currently selected item by using the select( )
method with a zero-based integer index.
int getItemCount( )
void select(int index)
• Given an index, you can obtain the name associated with the
item at that index by calling getItem( ),
String getItem(int index)
• Here, index specifies the index of the desired item.
Handling Lists
• To process list events, you will need to implement the
ActionListener interface.
• Each time a List item is double-clicked, an ActionEvent
object is generated.
• Its getActionCommand( ) method can be used to
retrieve the name of the newly selected item. Also,
each time an item is selected or deselected with a
single click, an ItemEvent object is generated. Its
getStateChange( ) method can be used to determine
whether a selection or deselection triggered this
event.
• getItemSelectable( ) returns a reference to the object
that triggered this event.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ListDemo" width=300 height=180> </applet> */
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Java™:
The Complete Reference
UNIT – 5 & Chapter – 24

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabi
• Introduction the AWT: Working with windows, graphics
and Text AWT classes, window fundamentals working with
frame windows creating a frame window in a an AWT Based
applet creating a window program displaying information
within a window Graphics working with color and fonts
setting the paint mode managing text output using font
metrics
• Using AWT controls, Layout Mangers, and Menus AWT
control fundamentals Labels, using buttons applying check
boxes, check box group choice controls, using lists Managing
scroll bars using a Text field, Using a Text area understanding
layout managers Menu bars and Menus dialog boxes, file
dialog Overriding paint()

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Controls
• The AWT supports the following types of controls:
– Labels
– Push buttons
– Check boxes
– Choice lists
– Lists
– Scroll bars
– Text editing

These controls are subclasses of Component.


RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Scroll Bars
• Scroll bars are used to select continuous values between a
specified minimum and maximum.
• Scroll bars may be oriented horizontally or vertically.
• Each end has an arrow that you can click to move the current
value of the scroll bar one unit in the direction of the arrow.
• The current value of the scroll bar relative to its minimum and
maximum values is indicated by the slider box (or thumb) for
the scroll bar.
• The slider box can be dragged by the user to a new position.
The scroll bar will then reflect this value. In the background
space on either side of the thumb, the user can click to cause
the thumb to jump in that direction by some increment larger
than 1.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Scroll Bars
• Scrollbar defines the following constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int
min, int max) throws HeadlessException
style is Scrollbar.VERTICAL, or Scrollbar.HORIZONTAL
• To set its parameters by using setValues( ),
void setValues(int initialValue, int thumbSize, int min, int max)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Scroll Bars
• To obtain the current value of the scroll bar, call getValue(). It
returns the current setting.
• To set the current value, call setValue( ).
int getValue( )
void setValue(int newValue)
• Retrieve the minimum and maximum values via
int getMinimum( )
int getMaximum( )
• By default, 1 is the increment added to or subtracted from the
scroll bar each time it is scrolled up or down one line. You can
change this increment by calling setUnitIncrement( ).
• By default, page-up and page-down increments are 10. You can
change this value by calling setBlockIncrement( ).

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Handling Scroll Bars
• To process scroll bar events, you need to implement the
AdjustmentListener interface.
• Each time a user interacts with a scroll bar, an
AdjustmentEvent object is generated.
• Its getAdjustmentType( ) method can be used to
determine the type of the adjustment.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Demonstrate scroll bars.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SBDemo" width=300 height=200> </applet> */
public class SBDemo extends Applet
implements AdjustmentListener, MouseMotionListener {
String msg = "";
Scrollbar vertSB, horzSB;
public void init() {
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
add(vertSB);
add(horzSB);
// register to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me) {
}
// Display current value of scroll bars.
public void paint(Graphics g) {
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
// show current mouse drag position
g.drawString("*", horzSB.getValue(),vertSB.getValue());
}
}
TextArea
• TextArea handle multiline text. The AWT includes a simple
multiline editor called TextArea.
TextArea( ) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str, int numLines, int numChars) throws HeadlessException
TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException
• Here, numLines specifies the height, in lines, of the text area, and numChars
specifies its width, in characters. Initial text can be specified by str. In the fifth form,
you can specify the scroll bars that you want the control to have. sBars must be one
of these values:

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
TextArea
• TextArea is a subclass of TextComponent. Therefore, it
supports the getText( ), setText( ), getSelectedText( ),
select( ), isEditable( ), and setEditable( ) methods.
• TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int endIndex)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo" width=300 height=250>
</applet>
*/
public class TextAreaDemo extends Applet {
public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
Layout Managers
• A layout manager automatically arranges controls within a window by
using some type of algorithm.
• It is possible to lay out Java controls by manual, but
– it is very tedious to manually lay out a large number of
components.
– The width and height information is not yet available when you
need to arrange some controls.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the
LayoutManager interface.
• The layout manager is set by the setLayout( ) method.
• If no call to setLayout( ) is made, then the default layout manager is
used.
• Whenever a container is resized (or sized for the first time), the
layout manager is used to position each of the components within it.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Layout Managers
void setLayout(LayoutManager layoutObj)
• Here, layoutObj is a reference to the desired layout manager.
• If you wish to disable the layout manager and position components
manually, pass null for layoutObj.
• Each layout manager keeps track of a list of components that are
stored by their names.
• The layout manager is notified each time you add a component to a
container.
• Whenever the container needs to be resized, the layout manager is
consulted via its minimumLayoutSize( ) and preferredLayoutSize( )
methods.
• Each component that is being managed by a layout manager contains
the getPreferredSize( ) and getMinimumSize( ) methods. These
return the preferred and minimum size required to display each
component.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Layout Managers
• Java has several predefined LayoutManager classes.
– FlowLayout
– BorderLayout
– GridLayout
– CardLayout
– GridBagLayout
– BoxLayout

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
FlowLayout
• FlowLayout is the default layout manager.
• FlowLayout implements a simple layout style, which is similar to
how words flow in a text editor.
• The direction of the layout is governed by the container’s
component orientation property, which, by default, is left to
right, top to bottom.
• Therefore, by default, components are laid out line-by-line
beginning at the upper-left corner.
• In all cases, when a line is filled, layout advances to the next
line.
• A small space is left between each component, above and
below, as well as left and right.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
FlowLayout
• FlowLayout constructors:
FlowLayout( )
default layout, which centers components and leaves five
pixels of space between each component.
FlowLayout(int how)
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
FlowLayout(int how, int horz, int vert)
specify the horizontal and vertical space left between components in
horz and vert, respectively.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Use left-aligned flow layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="FlowLayoutDemo" width=250 height=200>
</applet> */

public class FlowLayoutDemo extends Applet implements


ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init() {
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
// register to receive item events
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}}
BorderLayout
• The BorderLayout class implements a common layout style for top-
level windows.
• It has four narrow, fixed-width components at the edges and one
large area in the center.
• The four sides are referred to as north, south, east, and west. The
middle area is called the center.
• BorderLayout Constructors:
BorderLayout( )
BorderLayout(int horz, int vert)
• The first form creates a default border layout. The second allows you
to specify the horizontal and vertical space left between components
in horz and vert, respectively.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
BorderLayout
• BorderLayout defines the following constants that specify the regions:

When adding components, you will use these constants with the
following form of add( ), which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies
where the component will be added.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/* <applet code="BorderLayoutDemo" width=400 height=200> </applet> */
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
Insets
• Insets specifies the space that a container must leave at each of its
edges. The space can be a border, a blank space, or a title.
• Sometimes you will want to leave a small amount of space between
the container that holds your components and the window that
contains it. To do this, override the getInsets( ) method that is
defined by Container.
Insets getInsets( )
• This method returns an Insets object that contains the top, bottom,
left, and right inset to be used when the container is displayed.
Insets(int top, int left, int bottom, int right)
• The values passed in top, left, bottom, and right specify the amount
of space between the container and its enclosing window.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import java.awt.*;
import java.applet.*;
/*
<applet code="InsetsDemo.class" width=300 height=200>
</applet>
*/

public class InsetsDemo extends Applet


{
public void init()
{
setBackground(Color.cyan);
setLayout(new BorderLayout());
add(new Button("RMI"),BorderLayout.NORTH);
add(new Button("SERVLET"),BorderLayout.EAST);
add(new Button("JDBC"),BorderLayout.SOUTH);
add(new Button("BEANS"),BorderLayout.WEST);
add(new Button("JAVA"),BorderLayout.CENTER);
}
public Insets getInsets()
{
return new Insets(20,30,20,30);
}
}
GridLayout
• GridLayout lays out components in a two-dimensional grid. When you
instantiate a GridLayout, you define the number of rows and columns.
• GridLayout constructors:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
• The first form creates a single-column grid layout.
• The second form creates a grid layout with the specified number of rows
and columns.
• The third form allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
• Either numRows or numColumns can be zero. Specifying numRows as zero
allows for unlimited-length columns. Specifying numColumns as zero allows
for unlimited-length rows.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Demonstrate GridLayout of 4×4 grid
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Calculator" width=300 height=300>
</applet>
*/

public class Calculator extends Applet implements ActionListener{


String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("%");
clear=new Button("clear");
EQ=new Button("=");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++) {
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++) {
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("+"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("-"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("*"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("/"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("%"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("="))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
CardLayout
• The CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as
a card that is why it is known as CardLayout.
• The CardLayout class is unique among the other layout managers in
that it stores several different layouts. Each layout can be thought of
as being on a separate index card in a deck that can be shuffled so
that any card is on top at a given time.
• This can be useful for user interfaces with optional components that
can be dynamically enabled and disabled upon user input. You can
prepare the other layouts and have them hidden, ready to be
activated when needed.
• constructors:
CardLayout( )
CardLayout(int horz, int vert)
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
CardLayout
void add(Component panelObj, Object name)

Commonly used methods of CardLayout class


void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100>
</applet>
*/
public class CardLayoutDemo extends Applet
implements ActionListener, MouseListener {
Checkbox winXP, winVista, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init() {
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);
cardLO = new CardLayout();
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// add Windows check boxes to a panel
Panel winPan = new Panel();
winPan.add(winXP);
winPan.add(winVista);
// add other OS check boxes to a panel
Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);
// add panels to card deck panel
osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
addMouseListener(this);
}
// Cycle through panels.
public void mousePressed(MouseEvent me) {
cardLO.next(osCards);
}
// Provide empty implementations for the other MouseListener
methods.
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {
cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}
}
}
GridBagLayout
• The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.
• The components may not be of same size.
• The key to the grid bag is that each component can be a different size, and
each row in the grid can have a different number of columns. This is why
the layout is called a grid bag. It’s a collection of small grids joined together.
• Each GridBagLayout object maintains a dynamic, rectangular grid of cells.
Each component occupies one or more cells known as its display area. Each
component associates an instance of GridBagConstraints. With the help of
constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in
order to determine component's size.
• GridBagLayout defines only one constructor, which is shown here:
GridBagLayout( )
• void setConstraints(Component comp, GridBagConstraints cons)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
GridBagLayout
• The location and size of each component in a grid bag are
determined by a set of constraints linked to it. The constraints are
contained in an object of type GridBagConstraints.
• Constraints include the height and width of a cell, and the placement
of a component, its alignment, and its anchor point within the cell.
• The general procedure for using a grid bag is to first create a new
GridBagLayout object and to make it the current layout manager.
Then, set the constraints that apply to each component that will be
added to the grid bag. Finally, add the components to the layout
manager.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
When a component is smaller than its cell, you can use the anchor field to specify where
within the cell the component’s top-left corner will be located.
There are three types of values that you can give to anchor.
// Use GridBagLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="GridBagDemo" width=250 height=200> </applet> */

public class GridBagDemo extends Applet


implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init() {
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
// Define check boxes.
winXP = new Checkbox("Windows XP ", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// Define the grid bag.
// Use default row weight of 0 for first row.
gbc.weightx = 1.0; // use a column weight of 1
gbc.ipadx = 200; // pad by 200 units
gbc.insets = new Insets(4, 4, 0, 0); // inset slightly from top left
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(winXP, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(winVista, gbc);
// Give second row a weight of 1.
gbc.weighty = 1.0;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac, gbc);
// Add the components.
add(winXP);
add(winVista);
add(solaris);
add(mac);
// Register to receive item events.
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
BoxLayout
• The BoxLayout is used to arrange the components
either vertically or horizontally.
• For this purpose, BoxLayout provides four constants.
• Fields of BoxLayout class
– public static final int X_AXIS
– public static final int Y_AXIS
– public static final int LINE_AXIS
– public static final int PAGE_AXIS
• Constructor of BoxLayout class
BoxLayout(Container c, int axis)
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
import java.awt.*;
import javax.swing.*;

public class BoxLayoutEx extends Frame {


Button buttons[];

public BoxLayoutEx () {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}

public static void main(String args[]){


BoxLayoutEx b=new BoxLayoutEx();
}
}
setLayout (new BoxLayout (this, BoxLayout.X_AXIS));
Menu Bars and Menus
• A menu bar displays a list of top-level menu choices. Each choice is
associated with a drop-down menu. This is implemented in the AWT by the
following classes: MenuBar, Menu, and MenuItem.
• a menu bar contains one or more Menu objects. Each Menu object contains
a list of MenuItem objects. Each MenuItem object represents something
that can be selected by the user.
• Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can
be created.
• It is also possible to include checkable menu items. These are menu options
of type CheckboxMenuItem and will have a check mark next to them when
they are selected.
• To create a menu bar, first create an instance of MenuBar. This class only
defines the default constructor.
• Next, create instances of Menu that will define the selections displayed on
the bar.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Menu Bars and Menus
• constructors for Menu:
Menu( ) throws HeadlessException
Menu(String optionName) throws HeadlessException
Menu(String optionName, boolean removable) throws HeadlessException
• Individual menu items are of type MenuItem
MenuItem( ) throws HeadlessException
MenuItem(String itemName) throws HeadlessException
MenuItem(String itemName, MenuShortcut keyAccel) throws HeadlessException

void setEnabled(boolean enabledFlag)


boolean isEnabled( )
void setLabel(String newName)
String getLabel( )

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Menu Bars and Menus
• CheckboxMenuItem - constructors:
CheckboxMenuItem( ) throws HeadlessException
CheckboxMenuItem(String itemName) throws HeadlessException
CheckboxMenuItem(String itemName, boolean on) throws HeadlessException

• Methods are
boolean getState( )
void setState(boolean checked)
MenuItem add(MenuItem item)
Menu add(Menu menu)
Object getItem( )

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MenuDemo1" width=250 height=250>
</applet>
*/
Dialog Boxes
• The Dialog control represents a top level window with a border and a
title used to take some form of input from the user.
• It inherits the Window class.
• Unlike Frame, it doesn't have maximize and minimize buttons.
• Constructors are
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[]) {
new DialogExample();
} }
FileDialog
• FileDialog control represents a dialog window from which the user
can select a file.

FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)
• FileDialog provides methods that allow you to determine the name of
the file and its path as selected by the user. Here are two examples:
String getDirectory( )
String getFile( )

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import java.awt.*;
import java.awt.event.*;
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// remove the window when closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
class FileDialogDemo {
public static void main(String args[]) {
// create a frame that owns the dialog
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
f.setSize(100, 100);
FileDialog fd = new FileDialog(f, "File Dialog");
fd.setVisible(true);
}
}
End of 5 Unit
Java™:
The Complete Reference
UNIT – 5 & Chapter – 23

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• Introduction the AWT: Working with windows,
graphics and Text AWT classes, window fundamentals
working with frame windows creating a frame
window in a an AWT Based applet creating a window
program displaying information within a window
Graphics working with color and fonts setting the
paint mode managing text output using font metrics
• Using AWT controls, Layout Mangers, and Menus
AWT control fundamentals Labels, using buttons
applying check boxes, check box group choice
controls, using lists Managing scroll bars using a Text
field, Using a Text area understanding layout
managers Menu bars and Menus dialog boxes, file
RCEW, Pasupula (V), Nandikotkur Road,
dialog Overriding paint() Near Venkayapalli, KURNOOL
AWT (Abstract Window Toolkit)
• 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 AWT contains numerous classes and methods that allow you to
create and manage windows.
• A common use of the AWT is in applets, it is also used to create stand-
alone windows that run in a GUI environment, such as Windows.
• To run applets, you need to use an applet viewer or a Java-compatible
web browser.
• Today, most Java programs employ user interfaces based on Swing.
Because Swing provides richer implementations than does the AWT of
some common GUI controls, such as buttons, lists, and check boxes.
• Swing is built on top of the AWT, many AWT classes are used either
directly or indirectly by Swing.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
AWT Classes
• The AWT classes are contained in the java.awt
package. It is one of Java’s largest packages.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Window Fundamentals
• The AWT defines windows according to a class
hierarchy that adds functionality and specificity
with each level.
• The two most common windows are those derived
from Panel, which is used by applets, and those
derived from Frame, which creates a standard
application window.
• Much of the functionality of these windows is
derived from their parent classes. Thus, a
description of the class hierarchies relating to
these two classes is fundamental to their
understanding. RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Component
• At the top of the AWT hierarchy is the Component
class.
• Component is an abstract class that encapsulates all
of the attributes of a visual component.
• All user interface elements that are displayed on the
screen and that interact with the user are subclasses
of Component.
• It defines over a hundred public methods that are
responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window,
and repainting.
• A Component object is responsible for remembering
the current foreground and background colors and
the currently selectedRCEW,
textPasupula
font. (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Container
• The Container is a component in AWT that can
contain another components like buttons, textfields,
labels etc.
• The Container class is a subclass of Component.
• It has additional methods that allow other
Component objects to be nested within it.
• Other Container objects can be stored inside of a
Container (since they are themselves instances of
Component). This makes for a multileveled
containment system.
• A container is responsible for laying out (that is,
positioning) any components that it contains. It does
RCEW, Pasupula (V), Nandikotkur Road,
this through the use of various layout managers.
Near Venkayapalli, KURNOOL
Panel
• The Panel is the container that doesn't contain title bar and
menu bars. It can have other components like button, textfield
etc.
• The Panel class is a concrete subclass of Container.
• It doesn’t add any new methods; it simply implements Container.
• A Panel may be thought of as a recursively nestable, concrete
screen component.
• Panel is the superclass for Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel
object.
• Panel is a window that does not contain a title bar, menu bar, or
border.
• This is why applet don’t show these items when it is run inside a
browser.
• When you run an applet using an applet viewer, the applet
viewer provides the title and border.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Panel
• Other components can be added to a Panel object
by its add( ) method (inherited from Container).
• Once these components have been added, you
can position and resize them manually using the
setLocation( ), setSize( ), setPreferredSize( ), or
setBounds( ) methods defined by Component.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.red);

f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new PanelExample();
}
}
Window
• The Window class creates a top-level window.
• A top-level window is not contained within any
other object; it sits directly on the desktop.
• Generally, you won’t create Window objects
directly. Instead, you will use a subclass of
Window called Frame.
• The window is the container that have no borders
and menu bars.
• You must use frame, dialog or another window for
creating a window.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Frame
• The Frame is the container that contain title bar and
can have menu bars. It can have other components
like button, textfield etc.
• It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners.
• If you create a Frame object from within an applet, it
will contain a warning message, such as “Java Applet
Window,” to the user that an applet window has been
created. This message warns users that the window
they see was started by an applet and not by software
running on their computer.
• When a Frame window is created by a stand-alone
application rather than an applet, a normal window is
created. RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Canvas
• It is not part of the hierarchy for applet or frame
windows, there is one other type of window that
you will find valuable: Canvas.
• Canvas encapsulates a blank window upon which
you can draw.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Working with Frame Windows
• Frame’s constructors:
Frame( )
creates a standard window that does not contain a title
Frame(String title)
creates a window with the title specified by title.
• To create simple awt example, you need a frame.
There are two ways to create a frame in AWT.
– By extending Frame class (inheritance)
– By creating the object of Frame class (association)

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
• Setting the Window’s Dimensions
void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)
To obtain the current size of a window
Dimension getSize( )
Hiding and Showing a Window
void setVisible(boolean visibleFlag)
Setting a Window’s Title
void setTitle(String newTitle)
Closing a Frame Window
windowClosing( )
//AWT Example by Inheritance
import java.awt.*;
class AWTFirstEx extends Frame{
AWTFirstEx(){
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}
public static void main(String args[]){
AWTFirstEx f=new AWTFirstEx();
}
}
// AWT Example by Association
import java.awt.*;
class AWTFirstEx {
AWTFirstEx(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
AWTFirstEx f=new AWTFirstEx ();
}
}
Creating a Frame Window in an Applet
• Creating a new frame window from within an applet.
• First, create a subclass of Frame.
• Next, override any of the standard applet methods, such as
init( ), start( ), and stop( ), to show or hide the frame as
needed.
• Finally, implement the windowClosing( ) method of
theWindowListener interface, calling setVisible(false) when
the window is closed.
• Once you have defined a Frame subclass, you can create an
object of that class. This causes a frame window to come
into existence, but it will not be initially visible. You make it
visible by calling setVisible( ). When created, the window is
given a default height and width. You can set the size of the
window explicitly by callingRCEW, Pasupula
the (V), )
setSize( Nandikotkur
method. Road,
Near Venkayapalli, KURNOOL
Creating a Frame Window in an Applet
// Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString("This is in frame window", 10, 40);
} RCEW, Pasupula (V), Nandikotkur Road,
} Near Venkayapalli, KURNOOL
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
// Create frame window.
public class AppletFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
public void paint(Graphics g) {
g.drawString("This is in applet window", 10, 20);
}
}
Events
• 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.
• Events can be broadly classified into two categories:
– Foreground Events - Those events which require the direct
interaction of user.
– Background Events - Those events that require the
interaction of end user are known as background events.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Event Handling
• Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs.
• This mechanism 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.
• The Delegation Event Model has the following key participants
namely:
– Event 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.
– Event 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.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Type of Events
Event Classes Listener Interfaces

ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
• Button
– public void addActionListener(ActionListener a){}
• MenuItem
– public void addActionListener(ActionListener a){}
• TextField
– public void addActionListener(ActionListener a){}
– public void addTextListener(TextListener a){}
• TextArea
– public void addTextListener(TextListener a){}
• Checkbox
– public void addItemListener(ItemListener a){}
• Choice
– public void addItemListener(ItemListener a){}
• List
– public void addActionListener(ActionListener a){}
– public void addItemListener(ItemListener a){}
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
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.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
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.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf=new TextField(); //create components
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);

add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Mouse Events

public abstract void mouseClicked(MouseEvent e);


public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements
MouseListener{
Label l;
MouseListenerExample(){ public void mouseClicked(MouseEvent e) {
addMouseListener(this); l.setText("Mouse Clicked");
}
l=new Label(); public void mouseEntered(MouseEvent e) {
l.setBounds(20,50,100,20); l.setText("Mouse Entered");
add(l); }
setSize(300,300); public void mouseExited(MouseEvent e) {
setLayout(null); l.setText("Mouse Exited");
setVisible(true); }
} public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="MouseEventEx.class" width=200 height=300></applet> */
public class MouseEventEx extends Applet
{
int x,y;
public void init()
{
add a=new add();
addMouseListener(a);
}
public void paint(Graphics g) {
g.fillOval(x,y,30,30);
}
class add implements MouseListener
{
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e)
{
x=e.getX();
y=e.getY();
repaint();
}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseExited(MouseEvent e){

}
}
}
Handling Events in a Frame Window

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Java™:
The Complete Reference
UNIT – 5 & Chapter – 23

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus
• Introduction the AWT: Working with windows,
graphics and Text AWT classes, window fundamentals
working with frame windows creating a frame
window in a an AWT Based applet creating a window
program displaying information within a window
Graphics working with color and fonts setting the
paint mode managing text output using font metrics
• Using AWT controls, Layout Mangers, and Menus
AWT control fundamentals Labels, using buttons
applying check boxes, check box group choice
controls, using lists Managing scroll bars using a Text
field, Using a Text area understanding layout
managers Menu bars and Menus dialog boxes, file
RCEW, Pasupula (V), Nandikotkur Road,
dialog Overriding paint() Near Venkayapalli, KURNOOL
Creating a Windowed Program
• Although creating applets is a common use for
Java’s AWT, it is also possible to create stand-alone
AWT-based applications.
• To do this, simply create an instance of the
window or windows you need inside main( ).

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Program – 1 Create an AWT-based application – Key Events.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
// Create a frame window.
public class AppWindowKeyEvnt extends Frame {
String keymsg = "This is a test.";

public AppWindowKeyEvnt() {
addKeyListener(new MyKeyAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
g.drawString(keymsg, 10, 40);
}
// Create the window.
public static void main(String args[]) {
AppWindowKeyEvnt appwin = new AppWindowKeyEvnt();
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
class MyKeyAdapter extends KeyAdapter {
AppWindowKeyEvnt appWindow;
public MyKeyAdapter(AppWindowKeyEvnt appWindow) {
this.appWindow = appWindow;
}
public void keyTyped(KeyEvent ke) {
appWindow.keymsg += ke.getKeyChar();
appWindow.repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
// Program – 2 Create an AWT-based application – Mouse Event.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
// Create a frame window.
public class AppWindowMouseEvnt extends Frame {
String mousemsg = "";
int mouseX=30, mouseY=30;

public AppWindowMouseEvnt() {
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
g.drawString(mousemsg, mouseX, mouseY);
}
// Create the window.
public static void main(String args[]) {
AppWindowMouseEvnt appwin = new AppWindowMouseEvnt();
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
class MyMouseAdapter extends MouseAdapter {
AppWindowMouseEvnt appWindow;
public MyMouseAdapter(AppWindowMouseEvnt appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent me) {
appWindow.mouseX = me.getX();
appWindow.mouseY = me.getY();
appWindow.mousemsg = "Mouse Down at " + appWindow.mouseX +
", " + appWindow.mouseY;
appWindow.repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
Displaying Information Within a
Window
• A window is a container for information.
Although we have already output small
amounts of text to a window in the preceding
examples.
• Java’s text-handling, graphics-handling, and
font-handling.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Working with Graphics
• The AWT supports a rich collection of graphics
methods.
• All graphics are drawn relative to a window. This can
be the main window of an applet, a child window of
an applet, or a stand-alone application window.
• The origin of each window is at the top-left corner
and is 0,0. Coordinates are specified in pixels. All
output to a window takes place through a graphics
context.
• A graphics context is encapsulated by the Graphics
class and is obtained in two ways:
1. It is passed to an applet when one of its various methods,
such as paint( ) or update( ), is called.
2. It is returned by the getGraphics( ) method of
RCEW, Pasupula (V), Nandikotkur Road,
Component. Near Venkayapalli, KURNOOL
Working with Graphics
• The Graphics class defines a number of drawing functions.
• Each shape can be drawn edge-only or filled.
• Objects are drawn and filled in the currently selected graphics
color, which is black by default.
• When a graphics object is drawn that exceeds the dimensions of
the window, output is automatically clipped.
• Drawing Lines - Lines are drawn by means of the drawLine()
method
void drawLine(int startX, int startY, int endX, int endY)
• Drawing Rectangles - The drawRect( ) and fillRect( ) methods
display an outlined and filled rectangle, respectively.
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
To draw a rounded rectangle:
void drawRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
RCEW,
void fillRoundRect(int top, int left, Pasupula
int width, (V), Nandikotkur
int height,int xDiam, intRoad,
yDiam)
Near Venkayapalli, KURNOOL
// Draw lines
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 height=200>
</applet>
*/
public class Lines extends Applet {
public void paint(Graphics g) {
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
}
}
// Draw rectangles
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet {
public void paint(Graphics g) {
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}
Working with Graphics
• Drawing Ellipses and Circles - To draw an ellipse, use
drawOval( ). To fill an ellipse, use fillOval( ).
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
• Drawing Arcs - Arcs can be drawn with drawArc( ) and
fillArc(),
void drawArc(int top, int left, int width, int height, int
startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int
startAngle,int sweepAngle)
• Drawing Polygons - It is possible to draw arbitrarily shaped
figures using drawPolygon( ) and fillPolygon( ),
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[RCEW,
], intPasupula
y[ ], int (V), Nandikotkur Road,
numPoints)
Near Venkayapalli, KURNOOL
// Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
public class Ellipses extends Applet {
public void paint(Graphics g) {
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}
// Draw Arcs
import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 height=200>
</applet>*/

public class Arcs extends Applet {


public void paint(Graphics g) {
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}
// Draw Polygon
import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>*/

public class HourGlass extends Applet {


public void paint(Graphics g) {
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Working with Graphics
• Sizing Graphics - To size a graphics object to fit the
current size of the window in which it is drawn. To do so,
first obtain the current dimensions of the window by
calling getSize( ) on the window object. It returns the
dimensions of the window encapsulated within a
Dimension object. Once you have the current size of the
window, you can scale your graphical output accordingly.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Resizing output to fit the current size of a window.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="ResizeMe" width=200 height=200></applet>*/

public class ResizeMe extends Applet {


final int inc = 25;
int max = 500;
int min = 200;
Dimension d;
public ResizeMe() {
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
int w = (d.width + inc) > max?min :(d.width + inc);
int h = (d.height + inc) > max?min :(d.height + inc);
setSize(new Dimension(w, h));
}
});
}
public void paint(Graphics g) {
d = getSize();
g.drawLine(0, 0, d.width-1, d.height-1);
g.drawLine(0, d.height-1, d.width-1, 0);
g.drawRect(0, 0, d.width-1, d.height-1);
}
}
Working with Color
• Java supports color in a portable, device-
independent fashion. The AWT color system
allows you to specify any color you want.
• Color is encapsulated by the Color class.
Color(int red, int green, int blue)
The constructor takes three integers that specify the color as a mix of red,
green, and blue(RGB). These values must be between 0 and 255
Color(int rgbValue)
The second color constructor takes a single integer that contains the mix of red, green, and
blue packed into an integer. The integer is organized with red in bits 16 to 23, green in bits
8 to 15, and blue in bits 0 to 7.

Color(float red, float green, float blue)


The final constructor, Color(float, float, float), takes three float values (between 0.0 and
1.0) that specify the relative mix of red, green,
RCEW, and blue.
Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
hue-saturation-brightness (HSB)
Hue, Saturation, and Brightness
• The hue-saturation-brightness (HSB) color model is an
alternative to red-green-blue (RGB) for specifying particular
colors.
• hue is a wheel of color. The hue is specified with a number
between 0.0 and 1.0 (the colors are approximately red, orange,
yellow, green, blue,
• indigo, and violet).
• Saturation is another scale ranging from 0.0 to 1.0, representing
light pastels to intense hues.
• Brightness values also range from 0.0 to 1.0, where 1 is bright
white and 0 is black.
• Color supplies two methods that let you convert between RGB
and HSB.
static int HSBtoRGB(float hue, float saturation, float brightness)
static float[ ] RGBtoHSB(int red,Pasupula
RCEW, int green,
(V),int blue, floatRoad,
Nandikotkur values[ ])
Near Venkayapalli, KURNOOL
hue-saturation-brightness (HSB)
• You can obtain the red, green, and blue components
of a color independently using
int getRed( )
int getGreen( )
int getBlue( )
• To obtain a packed, RGB representation of a color,
int getRGB( )
• By default, graphics objects are drawn in the current
foreground color. You can change this color by calling
void setColor(Color newColor)
• Obtain the current color by calling
Color getColor( ) RCEW,Near
Pasupula (V), Nandikotkur Road,
Venkayapalli, KURNOOL
// Demonstrate color.
import java.awt.*;
import java.applet.*;
/* <applet code="ColorDemo" width=300 height=200>
</applet> */
public class ColorDemo extends Applet {
// draw lines
public void paint(Graphics g) {
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
g.setColor(c1);
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.setColor(c2);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.setColor(c3);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
g.setColor(Color.red);
g.drawOval(10, 10, 50, 50);
g.fillOval(70, 90, 140, 100);
g.setColor(Color.blue);
g.drawOval(190, 10, 90, 30);
g.drawRect(10, 10, 60, 50);
g.setColor(Color.cyan);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
}
}
Setting the Paint Mode
• The paint mode determines how objects are drawn in a window.
By default, new output to a window overwrites any preexisting
contents.
• However, it is possible to have new objects XORed onto the
window by using setXORMode( ), as follows:
void setXORMode(Color xorColor)
• Here, xorColor specifies the color that will be XORed to the
window when an object is drawn.
• The advantage of XOR mode is that the new object is always
guaranteed to be visible no matter what color the object is
drawn over.
• To return to overwrite mode, call setPaintMode( ), shown here:
void setPaintMode( )
• In general, you will want to use overwrite mode for normal
output, and XOR mode for special purposes.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
// Demonstrate XOR mode.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/* <applet code="XORDemo" width=400 height=200> </applet> */

public class XORDemo extends Applet {


int chsX=100, chsY=100;
public XORDemo() {
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent me) {
int x = me.getX();
int y = me.getY();
chsX = x-10;
chsY = y-10;
repaint();
}
});
}
public void paint(Graphics g) {
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.setColor(Color.blue);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.setColor(Color.green);
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.setColor(Color.red);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
g.setColor(Color.cyan);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
// xor cross hairs
g.setXORMode(Color.black);
g.drawLine(chsX-10, chsY, chsX+10, chsY);
g.drawLine(chsX, chsY-10, chsX, chsY+10);
g.setPaintMode();
}
}
Working with Fonts
• The AWT supports multiple type fonts.
• typesetting to become an important part of computer-
generated documents and displays.
• The AWT provides flexibility by abstracting font-
manipulation operations and allowing for dynamic selection
of fonts.
• Fonts have a family name, a logical font name, and a face
name.
• The family name is the general name of the font, such as
Courier.
• The logical name specifies a category of font, such as
Monospaced.
• The face name specifies a specific font, such as Courier
Italic.
• Fonts are encapsulated RCEW,
by thePasupula
Font class.
(V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
• Determining the Available Fonts - to know which
fonts are available on your machine
String[ ] getAvailableFontFamilyNames( )
• The getAllFonts( ) method returns an array of Font
objects for all of the available fonts.
Font[ ] getAllFonts( )
• These methods are members of
GraphicsEnvironment, you need a
GraphicsEnvironment reference to call them. You can
obtain this reference by using the
getLocalGraphicsEnvironment( ) static method, which
is defined by GraphicsEnvironment.
static GraphicsEnvironment getLocalGraphicsEnvironment( )
// Display All Fonts
/*
<applet code="ShowFonts" width=550 height=60> </applet>
*/
import java.applet.*;
import java.awt.*;
public class ShowFonts extends Applet {
public void paint(Graphics g) {
String msg = "";
String FontList[];
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
msg += FontList[i] + " ";
g.drawString(msg, 4, 16);
}
}
Creating and Selecting a Font
• To select a new font, you must first construct a Font
object that describes that font.
Font(String fontName, int fontStyle, int pointSize)
• Here, fontName specifies the name of the desired
font. The name can be specified using either the
logical or face name. All Java environments will
support the following fonts: Dialog, DialogInput, Sans
Serif, Serif, and Monospaced.
• Dialog is the font used by your system’s dialog boxes.
Dialog is also the default if you don’t explicitly set a
font. You can also use any other fonts supported by
your particular environment, but be careful—these
RCEW, Pasupula (V), Nandikotkur Road,
other fonts may not be universally available.
Near Venkayapalli, KURNOOL
Creating and Selecting a Font
• The style of the font is specified by fontStyle.
• It may consist of one or more of these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine
styles, OR them together.
• For example, Font.BOLD | Font.ITALIC specifies a
bold, italics style.
• The size, in points, of the font is specified by pointSize.
• To use a font that you have created, you must select it
using setFont( ), which is defined by Component.
void setFont(Font fontObj)
• Here, fontObj is the object that contains the desired
font. RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
// Show fonts.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="SampleFonts" width=200 height=100> </applet>
*/
public class SampleFonts extends Applet {
int next = 0;
Font f;
String msg;
public void init() {
f = new Font("Dialog", Font.PLAIN, 12);
msg = "Dialog";
setFont(f);
addMouseListener(new MyMouseAdapter(this));
}
public void paint(Graphics g) {
g.drawString(msg, 4, 20);
}
}
class MyMouseAdapter extends MouseAdapter {
SampleFonts sampleFonts;
public MyMouseAdapter(SampleFonts sampleFonts) {
this.sampleFonts = sampleFonts;
}
public void mousePressed(MouseEvent me) {
// Switch fonts with each mouse click.
sampleFonts.next++;
switch(sampleFonts.next) {
case 0:
sampleFonts.f = new Font("Dialog", Font.PLAIN, 12);
sampleFonts.msg = "Dialog";
break;
case 1:
sampleFonts.f = new Font("DialogInput", Font.PLAIN, 12);
sampleFonts.msg = "DialogInput";
break;
case 2:
sampleFonts.f = new Font("SansSerif", Font.PLAIN, 12);
sampleFonts.msg = "SansSerif";
break;
case 3:
sampleFonts.f = new Font("Serif", Font.PLAIN, 12);
sampleFonts.msg = "Serif"; break;
case 4:
sampleFonts.f = new Font("Monospaced", Font.PLAIN, 12);
sampleFonts.msg = "Monospaced";
break;
}
if(sampleFonts.next == 4) sampleFonts.next = -1;
sampleFonts.setFont(sampleFonts.f);
sampleFonts.repaint();
}
}
Obtaining Font Information
• Suppose you want to obtain information about the
currently selected font.
• To do this, you must first get the current font by
calling getFont( ).
Font getFont( )
• Once you have obtained the currently selected
font, you can retrieve information about it using
various methods defined by Font.

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
// Display font info.
import java.applet.*;
import java.awt.*;

/* <applet code="FontInfo" width=350 height=60> </applet> */


public class FontInfo extends Applet {
public void paint(Graphics g) {
Font f = g.getFont();
String fontName = f.getName();
String fontFamily = f.getFamily();
int fontSize = f.getSize();
int fontStyle = f.getStyle();
String msg = "Family: " + fontName;
msg += ", Font: " + fontFamily;
msg += ", Size: " + fontSize + ", Style: ";
if((fontStyle & Font.BOLD) == Font.BOLD)
msg += "Bold ";
if((fontStyle & Font.ITALIC) == Font.ITALIC)
msg += "Italic ";
if((fontStyle & Font.PLAIN) == Font.PLAIN)
msg += "Plain ";
g.drawString(msg, 4, 16);
}
}
Managing Text Output Using
FontMetrics
• Java supports a number of fonts.
• For most fonts, characters are not all the same
dimension—most fonts are proportional. Also, the
height of each character, the length of descenders
(the hanging parts of letters, such as y), and the
amount of space between horizontal lines vary
from font to font. Further, the point size of a font
can be changed.
• AWT includes the FontMetrics class to fill this.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Displaying Multiple Lines of Text
// Demonstrate multiline output.
import java.applet.*;
import java.awt.*;
/*
<applet code="MultiLine" width=300 height=100> </applet>
*/
public class MultiLine extends Applet {
int curX=0, curY=0; // current position
public void init() {
Font f = new Font("SansSerif", Font.PLAIN, 12);
setFont(f);
}
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics();
nextLine("This is on line one.", g);
nextLine("This is on line two.", g);
sameLine(" This is on same line.", g);
sameLine(" This, too.", g);
nextLine("This is on line three.", g); Pasupula (V), Nandikotkur Road,
RCEW,
} Near Venkayapalli, KURNOOL
// Advance to next line.
void nextLine(String s, Graphics g) {
FontMetrics fm = g.getFontMetrics();
curY += fm.getHeight(); // advance to next line
curX = 0;
g.drawString(s, curX, curY);
curX = fm.stringWidth(s); // advance to end of line
}
// Display on same line.
void sameLine(String s, Graphics g) {
FontMetrics fm = g.getFontMetrics();
g.drawString(s, curX, curY);
curX += fm.stringWidth(s); // advance to end of line
}
}
Centering Text
// Center text.
import java.applet.*;
import java.awt.*;
/* <applet code="CenterText" width=200 height=100> </applet> */
public class CenterText extends Applet {
final Font f = new Font("SansSerif", Font.BOLD, 18);
public void paint(Graphics g) {
Dimension d = this.getSize();
g.setColor(Color.white);
g.fillRect(0, 0, d.width,d.height);
g.setColor(Color.black);
g.setFont(f);
drawCenteredString("This is centered.", d.width, d.height, g);
g.drawRect(0, 0, d.width-1, d.height-1);
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(s)) / 2;
int y = (fm.getAscent() + (h - (fm.getAscent()+ fm.getDescent()))/2);
g.drawString(s, x, y);
}
}
Multiline Text Alignment
Java Database Connectivity(JDBC)

Mahesh K

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabus

• Accessing Databases with JDBC:


• Types of Drivers, JDBC Architecture, JDBC
classes and Interfaces, Basic steps in
developing JDBC applications, Creating a new
database and table with JDBC.
JDBC stands for Java Database Connectivity, which
is a standard Java API for database-independent
connectivity between the Java programming
language and a wide range of databases.

The JDBC library includes APIs for each of the tasks


mentioned below that are commonly associated
with database usage.

•Making a connection to a database.


•Creating SQL or MySQL statements.
•Executing SQL or MySQL queries in the database.
•Viewing & Modifying the resulting records.
JDBC is a specification that provides a complete set
of interfaces that allows for portable access to an
underlying database. Java can be used to write
different types of executables, such as −
•Java Applications
•Java Applets
•Java Servlets
•Java ServerPages (JSPs)
•Enterprise JavaBeans (EJBs).
All of these different executables are able to use a
JDBC driver to access a database, and take
advantage of the stored data.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models
for database access but in general, JDBC Architecture consists of
two layers −
• JDBC API: This provides the application-to-JDBC Manager
connection.
• JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.
The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to
access each data source. The driver manager is capable of
supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
JDBC Architecture
Common JDBC Components
• The JDBC API provides the following interfaces and classes
• DriverManager: This class manages a list of database
drivers. Matches connection requests from the java
application with the proper database driver using
communication sub protocol. The first driver that
recognizes a certain subprotocol under JDBC will be used
to establish a database Connection.
• Driver: This interface handles the communications with
the database server. You will interact directly with Driver
objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also
abstracts the details associated with working with Driver
objects.
Common JDBC Components
• Connection: This interface with all methods for
contacting a database. The connection object represents
communication context, i.e., all communication with
database is through connection object only.
• Statement: You use objects created from this interface to
submit the SQL statements to the database. Some
derived interfaces accept parameters in addition to
executing stored procedures.
• ResultSet: These objects hold data retrieved from a
database after you execute an SQL query using Statement
objects. It acts as an iterator to allow you to move
through its data.
• SQLException: This class handles any errors that occur in
a database application.
JAVA Installation
Install J2SE Development Kit 5.0 (JDK 5.0) from Java
Official Site.
• JAVA_HOME: This environment variable should
point to the directory where you installed the JDK,
e.g. C:\Program Files\Java\jdk1.5.0.
• CLASSPATH: This environment variable should
have appropriate paths set, e.g. C:\Program
Files\Java\jdk1.5.0_20\jre\lib.
• PATH: This environment variable should point to
appropriate JRE bin, e.g. C:\Program
Files\Java\jre1.5.0_20\bin.
Creating JDBC Application
There are following six steps involved in building a JDBC application
• Import the packages: Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so
you can open a communication channel with the database.
• Open a connection: Requires using the
DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database.
• Execute a query: Requires using an object of type Statement for
building and submitting an SQL statement to the database.
• Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
• Clean up the environment: Requires explicitly closing all database
resources versus relying on the JVM's garbage collection.
What is JDBC Driver
JDBC drivers implement the defined interfaces in the
JDBC API, for interacting with your database server.
For example, using JDBC drivers enable you to open
database connections and to interact with it by
sending SQL or database commands then receiving
results with Java.
The Java.sql package that ships with JDK, contains
various classes with their behaviors defined and their
actual implementations are done in third-party
drivers.
Third party vendors implements
the java.sql.Driver interface in their database driver.
JDBC Drivers Types

• JDBC driver implementations vary because of


the wide variety of operating systems and
hardware platforms in which Java operates.
Sun has divided the implementation types into
four categories,
Type 1,
Type 2,
Type 3, and
Type 4
Type 1: JDBC-ODBC Bridge Driver
• In a Type 1 driver, a JDBC bridge is used to access
ODBC drivers installed on each client machine. Using
ODBC, requires configuring on your system a Data
Source Name (DSN) that represents the target
database.
• When Java first came out, this was a useful driver
because most databases only supported ODBC access
but now this type of driver is recommended only for
experimental use or when no other alternative is
available.
• The JDBC-ODBC Bridge that comes with JDK 1.2 is a
good example of this kind of driver.
Type 2: JDBC-Native API
• In a Type 2 driver, JDBC API calls are converted into
native C/C++ API calls, which are unique to the
database. These drivers are typically provided by the
database vendors and used in the same manner as
the JDBC-ODBC Bridge. The vendor-specific driver
must be installed on each client machine.
• If we change the Database, we have to change the
native API, as it is specific to a database and they are
mostly obsolete now, but you may realize some
speed increase with a Type 2 driver, because it
eliminates ODBC's overhead.
• The Oracle Call Interface (OCI) driver is an example of
a Type 2 driver.
Type 3: JDBC-Net pure Java
• In a Type 3 driver, a three-tier approach is used to access
databases. The JDBC clients use standard network sockets to
communicate with a middleware application server. The
socket information is then translated by the middleware
application server into the call format required by the
DBMS, and forwarded to the database server.
• This kind of driver is extremely flexible, since it requires no
code installed on the client and a single driver can actually
provide access to multiple databases.
• You can think of the application server as a JDBC "proxy,"
meaning that it makes calls for the client application. As a
result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
• Your application server might use a Type 1, 2, or 4 driver to
communicate with the database, understanding the
nuances will prove helpful.
Type 4: 100% Pure Java
• In a Type 4 driver, a pure Java-based driver
communicates directly with the vendor's database
through socket connection. This is the highest
performance driver available for the database and is
usually provided by the vendor itself.
• This kind of driver is extremely flexible, you don't
need to install special software on the client or
server. Further, these drivers can be downloaded
dynamically.
• MySQL's Connector/J driver is a Type 4 driver.
Because of the proprietary nature of their network
protocols, database vendors usually supply type 4
drivers.
Which Driver should be Used?
• If you are accessing one type of database, such as
Oracle, Sybase, or IBM, the preferred driver type is 4.
• If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
• Type 2 drivers are useful in situations, where a type 3
or type 4 driver is not available yet for your database.
• The type 1 driver is not considered a deployment-
level driver, and is typically used for development and
testing purposes only.
Import JDBC Packages

• The Import statements tell the Java compiler


where to find the classes you reference in
your code and are placed at the very
beginning of your source code.

import java.sql.* ; // for standard JDBC programs


Register JDBC Driver
• You must register the driver in your program
before you use it. Registering the driver is the
process by which the Oracle driver's class file is
loaded into the memory, so it can be utilized as
an implementation of the JDBC interfaces.
• You need to do this registration only once in
your program.
• You can register a driver in one of two ways.
Approach I - Class.forName()
• The most common approach to register a driver is to
use Java's Class.forName() method, to dynamically
load the driver's class file into memory, which
automatically registers it. This method is preferable
because it allows you to make the driver registration
configurable and portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); }
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Approach II -
DriverManager.registerDriver()
• The second approach you can use to register a driver, is
to use the static
DriverManager.registerDriver() method.
• You should use the registerDriver() method if you are
using a non-JDK compliant JVM, such as the one
provided by Microsoft.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
} catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Database URL Formulation
After you've loaded the driver, you can establish a
connection using the
DriverManager.getConnection() method.
DriverManager.getConnection() methods are −
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
• Here each form requires a database URL. A database
URL is an address that points to your database.
• Formulating a database URL is where most of the
problems associated with establishing a connection
occurs.
Execute an SQL statement

• The Statement interface is used to execute


static SQL statements.
• A Statement object is instantiated using the
createStatement() method on the Connection
object.

Statement stmt = con.createStatement();


try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
st.executeUpdate("create table emp(eno number,ename varchar(10),sal
number)");

st.close();
con.close();
}
Methods of Statement object
• executeUpdate()
– Used to execute DDL (CREATE, ALTER, and DROP).
DML (INSERT, DELETE, UPDATE, etc) and DCL
statements
– The return value of this method is the number of
rows affected.

st.executeUpdate("create table emp(eno


number,ename varchar(10),sal number)");
Methods of Statement object

• executeQuery()
– Used to execute DQL statements such as SELECT.
– DQL statements only read data from database
tables.
– The return value of this method is a set of rows,
represented as a ResultSet object.

sql = "SELECT id, first, last, age FROM Employees";


ResultSet rs = stmt.executeQuery(sql);
Methods of Statement object
boolean execute(String SQL) : Returns a boolean
value of true if a ResultSet object can be retrieved;
otherwise, it returns false.
Use this method to execute SQL DDL statements or
when you need to use the truly dynamic SQL.

String sql = "UPDATE Employees set age=30 WHERE id=103";


Boolean ret = stmt.execute(sql);
import java.sql.*; Example-1
class OracleCon{ https://www.javatpoint.com/example-to-
public static void main(String args[]){ connect-to-the-oracle-database
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","syste
m",“manager");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();
}catch(Exception e){ System.out.println(e);}
}
}
interfaces of JDBC API
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
classes of JDBC API
• DriverManager class
• Blob class
• Clob class
• Types class
import java.sql.*; Example-createtable
public class CreateTable
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
st.executeUpdate("create table employee(eno number,ename varchar(10),sal number)");

st.close();
con.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException cnfe)
{
System.exit(1);
}
}
}
import java.sql.*;
import java.io.*; Example-insert
class IncorrectChoiceException extends Exception
{}
public class InsertTable {
public static void main(String args[])throws ClassNotFoundException, IOException
{
int i = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
Statement st = con.createStatement();
boolean wantMore = true;
while(wantMore) {
System.out.print("Enter employee number : ");
int eno = Integer.parseInt(br.readLine());
System.out.print("Enter name : ");
String ename = br.readLine();
System.out.print("Enter salary : ");
double sal = Double.parseDouble(br.readLine());

i += st.executeUpdate("insert into employee values(" + eno + ", \'" + ename + "\'," + sal + ")");

System.out.print("\nDo you want ot enter more records? (Y/N) : ");


String choice = br.readLine();

if(choice.equals("N") || choice.equals("n"))
wantMore = false;
else if(choice.equals("Y") || choice.equals("y"))
wantMore = true;
else throw new IncorrectChoiceException();
}
System.out.println("Update success : "+i+" rows updated");
st.close();
con.close();
}catch(SQLException se){
se.printStackTrace();
}catch(IncorrectChoiceException ic)
{
System.out.println("Error : Incorrect choice");
}
finally{
System.out.println("Total updates performed : "+i);
}
}
}
import java.sql.*; Example-update
import java.io.*;
public class UpdateTable {
public static void main(String s[ ]) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");
Statement st=con.createStatement();
con.setAutoCommit(false);

int i1=st.executeUpdate("update employee set sal=sal+1500 where eno=1");


int i2=st.executeUpdate("update employee set sal=sal+1000 where eno=2");

con.commit();
con.close();
}
catch(Exception e)
{
//con.RollBack();
e.printStackTrace();
}
}
}
import java.sql.*; Example-prepared
import java.io.*;
public class PreparedStmts {
public static void main(String s[]) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:dsn");

PreparedStatement ps=con.prepareStatement("select * from employee where empno=?");


BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

while(true)
{
System.out.println("Enter empno:");
int empno=Integer.parseInt(b.readLine());
if(empno==0)
break;
ps.setInt(1,empno);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println("ENAME: "+rs.getString(2));
System.out.println("SALARY: "+rs.getString(3));
}
rs.close();
}
con.close();
}
catch(Exception e)
{
System.out.println("The Exception is...."+e);
}
}
}
END

You might also like