Uploaded by jethvadhvanit56

10. AJP Assignment-II NOTE (1) (1) (2)

advertisement
Advance Java Programming
UNIT – II NOTES
1. Draw AWT class hierarchy.
2. Write a short note on components and containers.
Containers are integral part of AWT GUI components. A container
provides a space where a component can be located. A Container in
AWT is a component itself and it adds the capability to add
component to itself. Following are noticable points to be considered.
 Sub classes of Container are called as Containter. For example
Panel, Frame and Window.
 Container can add only Component to itself.
 A default layout is present in each container which can be
overridden using setLayout method.
Container
It is a generic container object which can contain other AWT
components.
Panel
Panel is the simplest container. It provides space in which any
other component can be placed, including other panels.
Frame
A Frame is a top-level window with a title and a border
Window
A Window object is a top-level window with no borders and no
menubar.
3. Explain various controls of component class.
(note need to write constructor n methods if any control asked
seperatly from ppt)
Component
A Component is an abstract super class for GUI controls and it
represents an object with graphical representation.
Label
A Label object is a component for placing text in a container.
Button
This class creates a labeled button.
Check Box
A check box is a graphical component that can be in either
an on (true) or off (false) state.
Check Box Group
The CheckboxGroup class is used to group the set of checkbox.
List
The List component presents the user with a scrolling list of text
items.
Text Field
A TextField object is a text component that allows for the editing of a
single line of text.
Text Area
A TextArea object is a text component that allows for the editing of a
multiple lines of text.
A Choice control is used to show pop up menu of choices. Selected
choice is shown on the top of the menu.
Canvas
A Canvas control represents a rectangular area where application
can draw something or can receive inputs created by user.
Image
An Image control is superclass for all image classes representing
graphical images.
Scroll Bar
A Scrollbar control represents a scroll bar component in order to
enable user to select from range of values.
Dialog
A Dialog control represents a top-level window with a title and a
border used to take some form of input from the user.
File Dialog
A FileDialog control represents a dialog window from which the user
can select a file.
4. Describe methods of List control.
List class is used to create a list with multiple values, allowing a user
to select any of the values. When a value is selected from List,
an ItemEvent is
generated,
which
is
handled
by
implementing ItemListener interface. List is another component in AWT
which extends Component class.
Constructors of List
Constructor
public List()
public List(int rows)
Description
Creates a scrolling list.
Creates a List with a number of rows.
Methods of List class
public List(int rows,
boolean mode)
Creates a List with a number of rows,
allowing us to select multiple values from
list if mode is true.
Methods
public void add(String item)
public void add(String item,
int index)
Description
Adds the item to the end of List.
Adds the item at a
specific index in the list.
Adds a specific ActionListener to
public void
listen an Action event generated
addActionListener(ActionListener
when item is selected from this
al)
list.
Adds a specific ItemListener to
public void
listen an Item event generated
addItemListener(ItemListener al) when item is selected from this
list.
Gets an item from a
public String getItem( int index)
specific index in the list.
public String getSelectedItem()
Gets the selected item in the list.
public String[] getSelectedItems() Gets the selected item in the list.
Gets the total number of rows in
public int getRows()
the list.
5. Explain the need of Layout Manager.
The LayoutManagers are used to arrange components in a
particular manner. The Java LayoutManagers facilitates us to
control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all
the classes of layout managers.
6. Explain different layout managers in Java in detail.
7.
In Java, Layout Managers is used for arranging the
components in order. LayoutMananger is an interface which
implements the classes of the layout manager.
Below are some of the class which are used for the representation of
layout manager.
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
Border Layout
BorderLayout is used, when we want to arrange the components in
five regions. The five regions can be north, south, east, west and the
centre. There are 5 types of constructor in Border Layout. They are
as following:
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
Example:
import java.awt.*;
import javax.swing.*;
public class BorderDemo1
{
JFrame frame;
BorderDemo1()
{
frame=new JFrame();
JButton box1=new JButton("**NORTH**");;
JButton box2=new JButton("**SOUTH**");;
JButton box3=new JButton("**EAST**");;
JButton box4=new JButton("**WEST**");;
JButton box5=new JButton("**CENTER**");;
frame.add(box1,BorderLayout.NORTH);
frame.add(box2,BorderLayout.SOUTH);
frame.add(box3,BorderLayout.EAST);
frame.add(box4,BorderLayout.WEST);
frame.add(box5,BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
}
public static void main(String[] args)
{
new BorderDemo1();
}
}
Copy
Grid Layout
Grid Layout is used, when we want to arrange the components in a
rectangular grid.
There are 3 types of constructor in Grid Layout. They are as
following:
1. GridLayout()
2. GridLayout(int rows, int columns)
3. GridLayout(int rows, int columns, inthgap, int vgap)
Example:
import java.awt.*;
import javax.swing.*;
public class GridDemo1{
JFrame frame1;
GridDemo1(){
frame1=new JFrame();
JButton box1=new JButton("*1*");
JButton box2=new JButton("*2*");
JButton box3=new JButton("*3*");
JButton box4=new JButton("*4*");
JButton box5=new JButton("*5*");
JButton box6=new JButton("*6*");
JButton box7=new JButton("*7*");
JButton box8=new JButton("*8*");
JButton box9=new JButton("*9*");
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.setLayout(new GridLayout(3,3));
frame1.setSize(500,500);
frame1.setVisible(true);
}
public static void main(String[] args) {
new GridDemo1();
}
}
Copy
Flow Layout
Flow Layout is used, when we want to arrange the components in a
sequence one after another.
There are 3 types of constructor in the Flow Layout. They are as
following:
1. FlowLayout()
2. FlowLayout(int align)
3. FlowLayout(int align, inthgap, intvgap)
Example:
import java.awt.*;
import javax.swing.*;
public class FlowDemo1{
JFrame frame1;
FlowDemo1(){
frame1=new JFrame();
JButton box1=new JButton("1");
JButton box2=new JButton("2");
JButton box3=new JButton("3");
JButton box4=new JButton("4");
JButton box5=new JButton("5");
JButton box6=new JButton("6");
JButton box7=new JButton("7");
JButton box8=new JButton("8");
JButton box9=new JButton("9");
JButton box10=new JButton("10");
frame1.add(box1);
frame1.add(box2);
frame1.add(box3);
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
frame1.add(box8);
frame1.add(box9);
frame1.add(box10);
frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
frame1.setSize(400,400);
frame1.setVisible(true);
}
public static void main(String[] args) {
new FlowDemo1();
}
}
Copy
8. What is the difference between GridLayout and
GridBagLayout manager?
A GridLayout puts all the components in a rectangular grid and
is divided into equal-sized rectangles and each component is
placed inside a rectangle whereas GridBagLayout is
a flexible layout manager that
aligns
the
components vertically and horizontally without requiring that
the
components
be
of
the
same
size.
Each GridBagLayout object
maintains
a
dynamic,
rectangular grid of cells with each component occupying one
or more cells called Component display area.
GridLayout
A GridLayout arranges the components in a rectangular grid. It
arranges component in the cells and each cell has the same
size.
Components
are
placed
in columns
and
rows. GridLayout(int
rows,
int
columns) takes two
parameters that are a column and a row.
Example
import java.awt.*;
import javax.swing.*;
public class GridLayoutTest{
GridLayoutTest() {
JFrame frame = new JFrame("GridLayout Test");
JButton button1, button2, button3, button4;
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button4 = new JButton("Button 4");
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.setLayout(new GridLayout(2,2));
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new GridLayoutTest();
}
}
Output
9.
GridBagLayout
A GridBagLayout extends
the
capabilities
of
the
GridLayout. GridBagLayout places component in each individual
cell in a grid and also allows the component to span to multiple
columns or rows. In order to use GridBagLayout, we need to
create
a GridBagConstraints object and
fill
appropriate
properties.
Example
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutTest extends JFrame {
public GridBagLayoutTest() {
setTitle("GridBagLayout Test");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 5;
gbc.gridy = 0;
add(new JButton("Button1"), gbc);
gbc.gridx = 0;
gbc.gridy = 5;
add(new JButton("Button2"), gbc);
gbc.gridx = 2;
gbc.gridy = 4;
add(new JButton("Button3"), gbc);
}
public static void main(String[] args) {
GridBagLayoutTest gbcTest = new GridBagLayoutTest();
gbcTest.setSize(300,300);
gbcTest.setVisible(true);
gbcTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output
10.
Write a note on delegation event model.
The Delegation Event model is defined to handle events in
GUI programming languages. The GUI stands for Graphical User
Interface, where a user graphically/visually interacts with the
system.
The GUI programming is inherently event-driven; whenever a user
initiates an activity such as a mouse activity, clicks, scrolling, etc.,
each is known as an event that is mapped to a code to respond to
functionality to the user. This is known as event handling.
Event Processing in Java
Java support event processing since Java 1.0. It provides support
for AWT ( Abstract Window Toolkit), which is an API used to develop
the Desktop application. In Java 1.0, the AWT was based on
inheritance. To catch and process GUI events for a program, it should
hold subclass GUI components and override action() or
handleEvent() methods. The below image demonstrates the event
processing.
But, the modern approach for event processing is based on the
Delegation Model. It defines a standard and compatible mechanism
to generate and process events. In this model, a source generates an
event and forwards it to one or more listeners. The listener waits until
it receives an event. Once it receives the event, it is processed by the
listener and returns it. The UI elements are able to delegate the
processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the
application logic is completely separated from the interface logic.
In this model, the listener must be connected with a source to receive
the event notifications. Thus, the events will only be received by the
listeners who wish to receive them. So, this approach is more
convenient than the inheritance-based event model (in Java 1.0).
In the older model, an event was propagated up the containment until
a component was handled. This needed components to receive
events that were not processed, and it took lots of time. The
Delegation Event model overcame this issue.
Basically, an Event Model is based on the following three
components:
o
Events
o
Events Sources
o
Events Listeners
Events
The Events are the objects that define state change in a source. An
event can be generated as a reaction of a user while interacting with
GUI elements. Some of the event generation activities are moving the
mouse pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also consider many
other user operations as events.
The Events may also occur that may be not related to user
interaction, such as a timer expires, counter exceeded, system
failures, or a task is completed, etc. We can define events for any of
the applied actions.
Event Sources
A source is an object that causes and generates an event. It
generates an event when the internal state of the object is changed.
The sources are allowed to generate several different types of
events.
A source must register a listener to receive notifications for a specific
event. Each event contains its registration method. Below is an
example:
1.
public void addTypeListener (TypeListener e1)
From the above syntax, the Type is the name of the event, and e1 is
a reference to the event listener. For example, for a keyboard event
listener, the method will be called as addKeyListener(). For the
mouse
event
listener,
the
method
will
be
called
as addMouseMotionListener(). When an event is triggered using
the respected source, all the events will be notified to registered
listeners and receive the event object. This process is known as
event multicasting. In few cases, the event notification will only be
sent to listeners that register to receive them.
Some listeners allow only one listener to register. Below is an
example:
1.
public void addTypeListener(TypeListener e2) throws java.util
.TooManyListenersException
From the above syntax, the Type is the name of the event, and e2 is
the event listener's reference. When the specified event occurs, it will
be notified to the registered listener. This process is known
as unicasting events.
A source should contain a method that unregisters a specific type of
event from the listener if not needed. Below is an example of the
method that will remove the event from the listener.
1.
public void removeTypeListener(TypeListener e2?)
From the above syntax, the Type is an event name, and e2 is the
reference of the listener. For example, to remove the keyboard
listener, the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that
generate the events. For example, the Component class contains the
methods to operate on the different types of events, such as adding
or removing them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers.
The listeners require two things; first, it must be registered with a
source; however, it can be registered with several resources to
receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of
interfaces. These interfaces can be found in the java.awt.event
package.
For example, the MouseMotionListener interface provides two
methods when the mouse is dragged and moved. Any object can
receive and process these events if it implements the
MouseMotionListener interface.
Types of Events
The events are categories into the following two categories:
The Foreground Events:
The foreground events are those events that require direct interaction
of the user. These types of events are generated as a result of user
interaction with the GUI component. For example, clicking on a
button, mouse movement, pressing a keyboard key, selecting an
option from the list, etc.
The Background Events :
The Background events are those events that result from the
interaction of the end-user. For example, an Operating system
interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that
provides control over the events and responses.
The Delegation Model
The Delegation Model is available in Java since Java 1.1. it provides
a new delegation-based event model using AWT to resolve the event
problems. It provides a convenient mechanism to support complex
Java programs.
Design Goals
The design goals of the event delegation model are as following:
o
It is easy to learn and implement
o
It supports a clean separation between application and GUI
code.
o
It provides robust event handling program code which is less
error-prone (strong compile-time checking)
o
It is Flexible, can enable different types of application models
for event flow and propagation.
o
It enables run-time discovery of both the component-generated
events as well as observable events.
o
It provides support for the backward binary compatibility with
the previous model.
Let's implement it with an example:
Java Program to Implement the Event Deligation Model
The below is a Java program to handle events implementing the
event deligation model:
TestApp.java:
import java.awt.*;
import java.awt.event.*;
public class TestApp {
public void search() {
// For searching
System.out.println("Searching...");
}
public void sort() {
// for sorting
System.out.println("Sorting....");
}
static public void main(String args[]) {
TestApp app = new TestApp();
GUI gui = new GUI(app);
}
}
class Command implements ActionListener {
static final int SEARCH = 0;
static final int SORT = 1;
int id;
TestApp app;
public Command(int id, TestApp app) {
this.id = id;
this.app = app;
}
public void actionPerformed(ActionEvent e) {
switch(id) {
case SEARCH:
app.search();
break;
case SORT:
app.sort();
break;
}
}
}
class GUI {
public GUI(TestApp app) {
Frame f = new Frame();
f.setLayout(new FlowLayout());
Command searchCmd = new Command(Command.SEARCH, app
);
Command sortCmd = new Command(Command.SORT, app);
Button b;
f.add(b = new Button("Search"));
b.addActionListener(searchCmd);
f.add(b = new Button("Sort"));
b.addActionListener(sortCmd);
List l;
f.add(l = new List());
l.add("Alphabetical");
l.add("Chronological");
l.addActionListener(sortCmd);
f.pack();
f.show();
}
}
Output:
11.
Explain how to create radio buttons using AWT.
n Java AWT, one can create Radio Buttons just like check boxes.
In order to create AWT radio buttons at run-time, we actually
create check box instances and then group it. As a result of
grouping, they act as Radio Buttons.
Radio Buttons are the special kind of check boxes grouped
together. In a group, we can select only one radio button item at a
time. AWT draws a check box in a square shape and check box in
a group as circle one. To follow this example, one should know
how to create a basic frame window. The article link below tells
how to create frame window.
Download