Java Unit-V Part-I
Java Unit-V Part-I
K A R M N A G A R - 505 4 8 1
(Approved by A IC T E, Ne w D elh i and A f f ili a te d to JNTU, Hyderabad)
UNIT-V
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
K A R M N A G A R - 505 4 8 1
(Approved by A IC T E, Ne w D elh i and A f f ili a te d to JNTU, Hyderabad)
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 [Link] package provides classes for AWT api such as TextField, Label, TextArea,
Radio Button, Check Box, Choice, List etc.
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
[Link].*;
classFirst extends
Frame{ First(){
Button b=new Button("click me");
[Link](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[]){ First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing .
Method Description
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: [Link]
[Link].*;
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
[Link](130,100,100, 40);//x axis, y axis, width, height
[Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500
height [Link](null);//using no layout
managers [Link](true);//making the
frame visible
}}
Containers
Java JFrame
The [Link] class is a type of container which inherits the [Link] class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create aGUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JFrameExample
{
public static void main(String s[]){
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
[Link](newFlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
[Link]("Button");
[Link](label);
[Link](button);
[Link](panel);
[Link](200, 300);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}}
JApplet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Appletclass.
[Link].*;
import [Link].*;
import
[Link].*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
[Link](30,40,150,20);
b=new JButton("Click");
[Link](80,150,70,40);
add(b);add(tf);
[Link](this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}}
In the above example, we have created all the controls in init() method because it is invoked
only once.
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300"height="300">
</applet>
</body>
</html>
JDialog
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 Dialogclass.
Constructor Description
JDialog(Frame owner, String title, It is used to create a dialog with the specified
boolean modal) title, owner Frame andmodality.
Java JDialog Example
[Link].*;
[Link].*;
[Link].*;
public class DialogExample {
private static JDialog d;
DialogExample(){
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link] (
newActionListener()
{
public void actionPerformed( ActionEvent e)
{
[Link](false);
}
}); Output:
JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
ComponentsJava
JButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
JButton class declaration
Let's see the declaration for [Link] class.
[Link].*;
public class ButtonExample{
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true); } }
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment image, and horizontal alignment.
)
Commonly used Methods:
Methods Description
void setText(String text) It defines the single line of text this component
will display.
Icon getIcon() It returns the graphic image that the label displays.
[Link].*;
classLabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](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.
[Link].*;
classTextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
f.s etLayout(null);
[Link](true);
} }
Java 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
import [Link];
[Link];
public class Example extends JFrame {
public Example() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
BorderLayout
The BorderLayout provides five constants for each region:
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.
Types of Event
● Foreground Events - Those events which require the direct interaction of [Link] are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard,selecting an item from list, scrolling the pageetc.
● BackgroundEvents-Thoseeventsthatrequiretheinteractionofenduserareknownas
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
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 [Link]'s have a brief introduction
to this model.
The Delegation Event Model has the following key participants namely:
● Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes
for sourceobject.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListenera){}
o MenuItem
o public void addActionListener(ActionListenera){}
o TextField
o public void addActionListener(ActionListenera){}
o public void addTextListener(TextListenera){}
o TextArea
o public void addTextListener(TextListenera){}
o Checkbox
o public void addItemListener(ItemListenera){}
o Choice
o public void addItemListener(ItemListenera){}
o List
o public void addActionListener(ActionListenera){}
o public void addItemListener(ItemListenera){}
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Sameclass
2. Otherclass
3. Annonymousclass
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
[Link] Adapter classes
Adapterclass Listenerinterface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
1. [Link].*;
[Link].*;
public class
AdapterExample{
Frame f;
AdapterExample()
{
f=new Frame("Window Adapter");
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent e) {
[Link](); } });
f.s etSize(400,400);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
newAdapterExample();
}}
Applets
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
o Plugin is required at client browser to execute applet.
The [Link] class 4 life cycle methods and [Link] class provides 1 life
cycle methods for an applet.
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life cycle methods
of applet.
1. 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.
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
1.//[Link]
[Link];
[Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome",150,150);
}
}
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer [Link]. Now Html file is not required but it is
for testing purpose only.
1. //[Link]
[Link]
;
[Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome to applet",150,150);
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt: