0% found this document useful (0 votes)
68 views27 pages

JAVA UNIT-5 Lecture Notes

The document discusses Java AWT and Swing. It introduces AWT components and limitations. It then covers Swing and the MVC architecture. It describes different layout managers and event handling in Swing using the delegation event model.

Uploaded by

Sai Nikhil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
68 views27 pages

JAVA UNIT-5 Lecture Notes

The document discusses Java AWT and Swing. It introduces AWT components and limitations. It then covers Swing and the MVC architecture. It describes different layout managers and event handling in Swing using the delegation event model.

Uploaded by

Sai Nikhil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

UNIT-5

AWT- Introduction:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Limitations of AWT
The AWT defines a basic set of controls, windows, and dialog boxes that support a reusable, but
limited graphical interface.
One reason for the limited nature of the AWT is that it translates its various visual components
into their corresponding, platform-specific equivalents or peers. This means that the look and
feel of a component is defined by the platform, not by java.
Because the AWT components use native code resources, they are referred to as heavy weight.
The use of native peers led to several problems. First, because of variations between operating
systems, a component might look, or even act, differently on different platforms.
Second, the look and feel of each component was fixed and could not be changed.
Third, the use of heavyweight components caused some frustrating restrictions.

MVC Architecture
Swing uses the model-view-controller architecture (MVC) as the fundamental design behind
each of its components. Essentially, MVC breaks GUI components into three elements. Each of
these elements plays a crucial role in how the component behaves.
Model: The model encompasses the state data for each component. There are different models
for different types of components. For example, the model of a scrollbar component might
contain information about the current position of its adjustable “thumb,” its minimum and
maximum values, and the thumb’s width (relative to the range of values). A menu, on the other
hand, may simply contain a list of the menu items the user can select from. Note that this
information remains the same no matter how the component is painted on the screen; model data
always exists independent of the component’s visual representation.
View: The view refers to how you see the component on the screen. For a good example of how
views can differ, look at an application window on two different GUI platforms. Almost all
window frames will have a titlebar spanning the top of the window. However, the titlebar may
have a close box on the left side (like the older MacOS platform), or it may have the close box
on the right side (as in the Windows 95 platform). These are examples of different types of views
for the same window object.
Controller: The controller is the portion of the user interface that dictates how the component
interacts with events. Events come in many forms — a mouse click, gaining or losing focus, a
keyboard event that triggers a specific menu command, or even a directive to repaint part of the
screen. The controller decides how each component will react to the event—if it reacts at all.

Java AWT Hierarchy( Components,Containers)


A component is an independent visual control, such as a push button.
A container holds a group of components. Examples of containers are Frame, Dialog, Applet,
Panel, Window.

Layout Managers
The Layout Managers are used to arrange components in a particular manner.

Flow Layout
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.
Example program:
import java.awt.*;
import javax.swing.*;
public class Demo23
{
public static void main(String args[])
{
JFrame f=new JFrame();
f.setLayout(new FlowLayout(FlowLayout.LEFT));
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");
JButton b10=new JButton("10");
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.add(b10);
f.setSize(300,300);
f.setVisible(true);
}
}

Border Layout
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.
Example Program:
import java.awt.*;
import javax.swing.*;
class Demo21
{
public static void main(String[] args)
{
JFrame f=new JFrame();
JButton b1=new JButton("A");;
JButton b2=new JButton("B");;
JButton b3=new JButton("C");;
JButton b4=new JButton("D");;
JButton b5=new JButton("E");;
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);
}
}

Grid Layout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Example program:
import java.awt.*;
import javax.swing.*;
public class Demo22
{
public static void main(String[] args)
{
JFrame 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.setLayout(new GridLayout(3,3));
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.setSize(300,300);
f.setVisible(true);
}
}

Card Layout
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.
Example Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Demo24 extends JFrame implements ActionListener
{
CardLayout card;
JButton b1,b2,b3;
Container c;
Demo24()
{
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space 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)
{
Demo24 f = new Demo24();
f.setSize(400,400);
f.setVisible(true);
f.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.
Example program:
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
class Demo25 extends JFrame
{
public static void main(String args[])
{
JFrame f=new JFrame();
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
f.setLayout(grid);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipady=20;
f.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
JButton b1=new JButton("Button One");
f.add(b1, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
f.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
JButton b4=new JButton("Button Four");
f.add(b4, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
f.add(new Button("Button Five"), gbc);
f.setSize(300, 300);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Event Handling- The Delegation event model
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.
Delegation Event Model:
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:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler.
Listener - It is also known as event handler.Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until
it receives an event. Once the event is received , the listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic
that generates the event. The user interface element is able to delegate the processing of an event
to the separate piece of code. In this model ,Listener needs to be registered with the source object
so that the listener can receive the event notification. This is an efficient way of handling the
event because the event notifications are sent only to those listener that want to receive them.
Steps involved in event handling
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
the method is now get executed and returns.

Event sources
Event classes
ActionEvent: The ActionEvent is generated when button is clicked or the item of a list is double
clicked.
KeyEvent: On entering the character the Key event is generated.
MouseEvent: This event indicates a mouse action occurred in a component.
TextEvent: The object of this class represents the text events.
WindowEvent: The object of this class represents the change in state of a window.
AdjustmentEvent: The object of this class represents the adjustment event emitted by
Adjustable objects.
ComponentEvent: The object of this class represents the change in state of a window.
ContainerEvent: The object of this class represents the change in state of a window.
MouseMotionEvent: The object of this class represents the change in state of a window.
PaintEvent: The object of this class represents the change in state of a window.

Event Listeners
ActionListener: This interface is used for receiving the action events.
ComponentListener: This interface is used for receiving the component events.
ItemListener: This interface is used for receiving the item events.
KeyListener: This interface is used for receiving the key events.
MouseListener: This interface is used for receiving the mouse events.
TextListener: This interface is used for receiving the text events.
WindowListener: This interface is used for receiving the window events.
AdjustmentListener: This interface is used for receiving the adjusmtent events.
ContainerListener: This interface is used for receiving the container events.
MouseMotionListener: This interface is used for receiving the mouse motion events.
FocusListener: This interface is used for receiving the focus events.

Handling Mouse Events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="evnt0" width=300 height=100>
</applet>
*/
public class evnt0 extends Applet implements MouseListener
{
String msg = "";
int mouseX = 0, mouseY = 0;
public void init()
{
this.addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "PAVAN";
repaint();
}
public void mouseEntered(MouseEvent me) { }
public void mouseExited(MouseEvent me) { }
public void mousePressed(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}

Handling Keyboard Events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="evnt2" width=300 height=100>
</applet>
*/
public class evnt2 extends Applet implements KeyListener
{
int X=20,Y=30;
String msg="chars :";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) { }
public void keyReleased(KeyEvent ke) { }
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}

Adapter classes,Inner classes, Anonymous Inner classes.


Adapter Class: 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.
Examples:
WindowAdapter for WindowListener
KeyAdapter for KeyListener
MouseAdapter for MouseListener

Example program (Handling WindowEvent using WindowAdapter):


// closing the frame when the user click on the close button of the frame window.
import java.awt.*;
import java.awt.event.*;
public class AdapterExample
{
Frame f;
AdapterExample()
{
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}

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.

Lifecycle of Java Applet


init(): is used to initialized the Applet. It is invoked only once.
start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
destroy(): is used to destroy the Applet. It is invoked only once.
paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used
for drawing oval, rectangle, arc etc.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Example-1:
import java.awt.*;
import java.applet.Applet;
/*
<applet code="app2" width=300 height=50>
</applet>
*/
public class app2 extends Applet
{
String msg;
public void init()
{
setBackground(Color.pink);
setForeground(Color.red);
msg = "shiva";
}
public void start()
{
msg = msg + " Rama";
}
public void paint(Graphics g)
{
msg = msg + " krishna";
g.drawString(msg, 10, 30);
}
}

To Run using appletviewer tool:


Compile: javac app2.java
Run: appletviewer app2.java
To Run in browser using html file
myapplet.html
<html>
<body>
<applet code="app2" width="300" height="300">
</applet>
</body>
</html>
Acces the above file from the browser.

Difference between Applet & JApplet:


You can use either one. Because JApplet actually extends Applet, much of the functionality is
identical. There are a few differences, however.
With JApplet, you have access to the content pane, which can be called using getContentPane().
If you have a content pane of your own (such as a panel) that you want to replace it with, you can
call setContentPane(). When you add components to your applet, you add them to the content
pane, not the frame.

Security Issues with Applet:


Java applet is run inside a web browser. But an applet is restricted in some areas, until it has been
deemed trustworthy by the end user. The security restriction is provided for protecting the user
by malicious code, like copy important information from the hard disk or deleting the files.
Generally, applets are loaded from the Internet and they are prevented from: the writing and
reading the files on client side. Some security issues to applet are following :
1. Applets are loaded over the internet and they are prevented to make open network
connection to any computer, except for the host, which provided the .class file. Because
the html page come from the host or the host specified codebase parameter in the applet
tag, with codebase taking precedence.

2. They are also prevented from starting other programs on the client. That means any
applet, which you visited, cannot start any rogue process on you computer. In UNIX,
applets cannot start any exec or fork processes. Applets are not allowed to invoke any
program to list the contents of your file system that means it cant invoke System.exit()
function to terminate you web browser. And they are not allowed to manipulate the
threads outside the applets own thread group.
3. Applets are loaded over the net. A web browser uses only one class loader that?s
established at start up. Then the system class loader can not be overloaded, overridden,
extended, replaced. Applet is not allowed to create the reference of their own class
loader.
4. They cant load the libraries or define the native method calls. But if it can define native
method calls then that would give the applet direct access to underlying computer.

passing parameters to applets


import java.awt.*;
import javax.swing.*;
/*
<applet code="app4" width=300 height=80>
<param name="username" value="shiva">
</applet>
*/
public class app4 extends JApplet
{
String Name;
public void start()
{
Name = getParameter("username");
if(Name == null)
Name = "VITS";
}
public void paint(Graphics g)
{
g.drawString("USER NAME: " + Name, 40, 70);
}
}

Swings:
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.
Unlike AWT, Java Swing provides platform-independent and lightweight components.

Swings vs AWT

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

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

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents
presentation and controller acts as an interface
between model and view.

Swing Controls/ Hierarchy of Swing Components


JFrame/JTextField/JButton/ActionEvents - Example
import java.awt.event.*;
import javax.swing.*;
public class Demo5 implements ActionListener
{
JTextField tf;
JFrame f;
JButton b;
Demo5()
{
f = new JFrame("Button Example");
tf = new JTextField();
tf.setBounds(50,50, 150,20);
b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.add(tf);
b.addActionListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to java class");
}
public static void main(String[] args)
{
new Demo5();
}
}

JLabel/JCheckBox/ItemEvents - Example:
import javax.swing.*;
import java.awt.event.*;
public class Demo6 implements ItemListener
{
JFrame f;
JLabel label;
JCheckBox checkbox1;
Demo6()
{
f= new JFrame("CheckBox Example");
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
f.add(checkbox1);
f.add(label);
checkbox1.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
label.setText("C++ Checkbox: " + (checkbox1.isSelected()==true?"selected":"not selected"));
}
public static void main(String args[])
{
new Demo6();
}
}

JTextField/JPassworField/Anonymour Inner Classes - Example


import javax.swing.*;
import java.awt.event.*;
public class Demo7
{
public static void main(String[] args)
{
JFrame f=new JFrame("Password Field Example");
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
JLabel l2=new JLabel("Password:");
l2.setBounds(20,75, 80,30);
JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
JLabel label = new JLabel();
label.setBounds(20,150, 250,50);
f.add(value);
f.add(l1);
f.add(label);
f.add(l2);
f.add(b);
f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data = "Username " + text.getText();
data = data + ", Password: " + new String(value.getPassword());
label.setText(data);
}
});
}
}

JRadioButton- Example:
import javax.swing.*;
import java.awt.event.*;
class Demo8 extends JFrame implements ActionListener
{
JRadioButton rb1,rb2;
JButton b;
Demo8()
{
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 Demo8();
}
}

JComboBox- Example:
import javax.swing.*;
import java.awt.event.*;
class Demo9
{
public static void main(String args[])
{
JFrame f = new JFrame("ComboBox Example");
String languages[]={"C","C++","C#","Java","PHP"};
JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
JLabel label = new JLabel();
label.setBounds(50,150,400,50);
f.add(cb);
f.add(label);
f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data = "Programming language Selected: "+
cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
}

JList- Example:
import javax.swing.*;
import java.awt.event.*;
public class Demo10
{
public static void main(String args[])
{
JFrame f= new JFrame();
JLabel label = new JLabel();
label.setSize(500,100);
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
JList<String> list1 = new JList<>(l1);
list1.setBounds(100,100, 75,75);
JButton b=new JButton("Show");
b.setBounds(200,150,80,30);
f.add(list1);
f.add(b);
f.add(label);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data = "";
if (list1.getSelectedIndex() != -1)
{
data = "Language Selected : " + list1.getSelectedValue();
label.setText(data);
}
}
});
}
}

You might also like