JAVA UNIT-5 Lecture Notes
JAVA UNIT-5 Lecture Notes
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.
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.
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.
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.
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
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.
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();
}
}
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);
}
}
});
}
}