0% found this document useful (0 votes)
177 views80 pages

Unit - 3 Event Driven Programming

This document provides an overview of event-driven programming in Java. It covers topics like graphics programming, AWT components, Swing components, frames, events, and layout management. It compares AWT and Swing, describing Swing as purely Java-based with pluggable look and feel, while AWT depends on native platform peers. It also provides code examples for creating frames and setting properties like icon and size.

Uploaded by

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

Unit - 3 Event Driven Programming

This document provides an overview of event-driven programming in Java. It covers topics like graphics programming, AWT components, Swing components, frames, events, and layout management. It compares AWT and Swing, describing Swing as purely Java-based with pluggable look and feel, while AWT depends on native platform peers. It also provides code examples for creating frames and setting properties like icon and size.

Uploaded by

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

UNIT - 3

EVENT DRIVEN
PROGRAMMING
Topics Covered:
• Graphics Programming
• Frame
• Components
• Working with 2D shapes
• Using Colors, Fonts, and Images
• Basics of Event Handling
• Event Handlers
• Adapter Classes
• Actions
• Mouse Events
• AWT Event Hierarchy
• Introduction to Swing
• Model –View-Controller Design pattern
• Buttons
• Layout Management
• Swing Components
Introduction Graphics Programming:
• “Graphical User Interface” a system whereby the user
interacts with a computer via a picture-based, graphic
medium.
• When Java 1.0 was introduced, it contained a class library
called Abstract Window ToolKit (AWT), for basic GUI
programming.
• The basic AWT library deals with user interface elements by
delegating their creation and behavior to the native GUI
toolkit on each target platform.
• The peer-based approach worked well for simple applications,
but it soon became apparent that it was fiendishly difficult
to write a high-quality portable graphics library that
depended on native user interface elements.
• The Internet Foundation Classes (IFC) where a graphics
library for Java originally developed by NetSpace
Communication and first released on December 16, 1996.
• On April 2, 1997,Sun MicroSystem and NetSpace Communications
Corporation incorporated IFC with other technologies to form
the Java Foundation Classes called a Swings.
• When developing a Java program it is important to select the
appropriate Java Graphical User Interface (GUI) components.
An Overview of AWT:
• AWT supports GUI Java programming.
• It is a portable GUI library for standard applications and/or
applets.
• The Abstract Window Toolkit provides the connection between
your application and the native GUI objects.
• The AWT provides a high level of abstraction for your Java
program since it hides you from the underlying details of the
GUI program will be running on.
• AWT features includes:
– A rich set of user interface components
– A robust event-handling model
– Graphics and imaging tools, including shape, color, and
font classes.
– Layout managers, for flexible window layouts that don’t
depend on a particular window size or screen resolution.
– Data transfer classes, for cut-and-paste through the
native platform clipboard.
• The AWT components depend on native code counterparts (called
peers) to handle their functionality.
• Thus these components are often called “ Heavy Weight
An Overview of Swing
• Swing implements a set of GUI components that build on AWT
technologies and provide a pluggable look and feel.
• Swing is implemented entirely in the Java programming
language and is based on the JDK1.1 Light Weight UI
Framework.

Swing Features Includes:


• All the features of AWT
• 100% pure Java certified versions of the existing AWT
component set (Buttons, Scrollbar, Label, etc..)
• A rich set of higher-level components ( such as tree view,
list box, and tapped panes)
• Pure Java design, no reliance on peers.
• Pluggable look and feel.
• These are over twice as many swing components available as
the AWT components.
• All this means Swing has the potential of finally fulfilling
the promise of Sun's "Write Once, Run Anywhere" slogan
AWT vs. Swing
• There are, of course both pros and cons to using either set
of components from the JFC in your applications.
AWT:
• Pros
– Speed – use of native peers speeds component performance
– Applet Portability: most web browsers support AWT classes
so AWT applets can run without the Java plugins
– Look and Feel: AWT components more closely reflect the
look and feel of the OS they run on.
• Cons
– Portability: use of native peers creates platforms
specific limitations. Some components may not function at
all on some platforms
– Third Party Development: the majority of components
makers, including Borland and Sun, base new component
development on Swing components. There is a much smaller
set of AWT components available, thus placing the burden
on the programmer to create his or her own AWT – based
components
– Features: AWT components do not support features like
icons and tool-tips.
Swing:
• Pros
– Portability: Pure Java design provides for fewer platform
specific limitations
– Behavior: Pure java designs allows for a greater range of
behavior for Swing components since they are not limited
by the native peers that AWT uses.
– Features: Swing supports a wider range of features like
icons and pop-up tool-tips for components.
– Vendor Support: Swing development is more active. Sun puts
much more energy into making Swing robust.
– Look and Feel: The pluggable look and feel lets you design
a single set of GUI components that can automatically have
the look and feel of any OS platform (Microsoft, Solaris,
Macintosh, etc.. ). It also makes it easier to make global
changes to your Java programs that provide greater
accessibility.
• Cons
– Applet Portability: Most Web browsers do not include the
Swing classes, so the Java plugins must be used.
– Performance: Swing Components are generally slower and
buggier than AWT, due to both the fact that they are pure
Java and to video issues on various platforms. Since
components handle their own painting, you may run into
graphical glitches.
• The reason to choose Swing are overwhelming:
– Swing has a rich and convenient set of user interface
elements.
– Swing has few dependencies on the underlying platform; it
is therefore less prone to platform-specific bugs.
• The Swing classes and components are contained in the
javax.swing package hierarchy.
Swing AWT

Light weight Components Heavy Weight Components

Complex Components Primitive Components

Pluggable look and feel Single Look and feel

Pure – Java Platform Not pure-java platform


independent dependent
Package javax. swing Package java.awt
FRAME:
• A top-level window is called a Frame in java.
• The AWT library has a class, called Frame, for this top
level.
• The Swing version of this class is called JFrame and extends
the Frame class.

1) By Extending JFrame Class:


import javax.swing.*;
class FrameCreate extends JFrame
{
public static void main(String args[])
{
FrameCreate fr = new FrameCreate();
fr.show();
fr.setSize(500,500);
}
}
2) By creating an object of JFrame:
import javax.swing.JFrame;
public class EmptyFrame
{
public static void main(String args[])
{
JFrame frame=new JFrame("EmptyFrame");
frame.setSize(600,600);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
• The Swing classes are placed in the javax.swing package.
• The package name indicates a javax - Java Extension package,
not a core package.
• There are two technical issues that we need to address in
every Swing program.
– All Swing components must be configured from the event
dispatches thread, the thread of control that passes
events such as mouse clicks and keystrokes to the user
interface components.
EventQueue.invokeLater(new Runnable()
{
public void run()
{
//statements
}
} );
– What should happen when the user closes the application’s
frame. For this particular program, we want the program to
exit. To select this behavior, use the statement,

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

• The JFrame class itself has only a few methods for changing
how frames look.
• Of course, most of the methods for working with size and
position of a frame come from the various super classes of
JFrame.
• Probably the most important methods, inherited from the base
class Frame, are the following ones:
• To get the screen size:
– Toolkit kit = Toolkit.getDefaultToolkit();
– Dimension screenSize = kit.getScreenSize();
– int screenWidth = screenSize.width;
– int screenHeight = screenSize.height;
• We also supply an icon. Because the representation of images
is also system dependent, we again need to use the toolkit to
load an image. Then, we set the image as the icon for the
frame.
– Image img = kit.getImage("icon.gif");
– setIconImage(img);
import javax.swing.*;
import java.awt.*;
public class SimpleFrameProperty {
public static void main(String args[])
{
SimpleFrame frame = new SimpleFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();

int screenWidth = screenSize.width;


int screenHeight = screenSize.height;
System.out.println("Frame Width: " + screenWidth +
"\n"+"Frame Height:
"+screenHeight);

Image img = kit.getImage("1.gif");


frame.setIconImage(img);
}
}
class SimpleFrame extends JFrame
{
public SimpleFrame()
{
//setSize(200,300);
}
}
Inheritance Hierarchy for the JFrame and JPanel
Classes:
COMPONENETS:
Displaying Information in a Component:
• Drawing the message string directly onto a frame, but that is
not considered good programming practice.
• In Java, frames are really designed to be containers for
components such as a menu bar and other user interface
elements.
• Draw normally on another component which is then added to the
frame.
The Structure of JFrame:
• Four panes are layered in a JFrame.
1) The Root Pane
2) Layered Pane
3) Glass Pane
4) Content Pane
• The root pane, layered pane and glass pane are required to
organize the menu bar and content pane to implement the look
and feel.
• The components are added into the content pane, using code
such as the following:
Container contentPane = frame.getContentPane();
Internal Structure of a JFrame:
• To add a single component to the frame onto which a message
is drawn.
• To draw on a component. Define a class that extends
JComponent or JPanel and override the paintComponent()
method.
• The paintComponent() takes one parameter of type Graphics.
• A Graphics object remembers a collection of settings for
drawing images and text, such as the font you set or the
current color.
• All drawing in Java must go through a Graphics Object.
• It has methods that draw patterns , images and text.
Syntax:
class MyComponent extends JComponent
{
public void paintComponent(Graphics g)
{
// code for drawing
}
}
• Each time a window needs to be redrawn, the event handler
notifies the component.
• Displaying text is considered a special kind of drawing. The
Graphics class has a drawString() method that has the
following syntax:
g.drawString(text,x,y);

• To draw the String “Hello World” in original window, roughly


start the string at coordinates (75,100).
• This means the first character in the string will start at a
position of 75 pixels to the right and 100 pixels down.
• Thus, the paintComponent() method looks like this:

class HelloWorldComponent extends Jcomponent


{
public void paintComponent(Graphics g)
{
g.drawString(“Hello World”, 75,100);
}
}
import javax.swing.*;
import java.awt.*;
public class DisplayMessage extends JPanel
{
public static void main(String args[])
{
JFrame frame=new JFrame("EmptyFrame");
frame.setSize(600,600);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

DisplayMessage msg = new DisplayMessage();


frame.add(msg);
}
public void paintComponent(Graphics g)
{
g.drawString("Hello World", 75,100);
}
}
Working with 2D Shapes:
• The Graphics class has methods to draw lines, rectangles,
ellipses, and so on.
• But those drawing operations are very limited.
• For example, varying the line thickness and rotating the
shapes is not possible.
• Later Java introduced the Java 2D library, which implements a
powerful set of graphical operations.
• To draw shapes in the Java 2D library, need to obtain an
object of the Graphics2D class.
• This class is a subclass of the Graphics class. To use it
simply use a cast, as follows:

public void paintComponent(Graphics g)


{
Graphics2D g2 = (Graphics2D)g;
----------
}
• The Java2D library organizes geometric shapes in an object-
oriented fashion.
• There are classes to represent lines, rectangle, and
• These classes all implement the Shape interface.
• To draw a shape, first create an object of a class that
implements the shape interface and then call the draw method
of the Graphics2D class.
• To handle Float and Double types, all the Line2D, Rectangle2D
and Ellipse2D classes contains two inner classes called as
Float and Double.

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class TestDraw
{
public static void main(String args[])
{
DrawFrame frm = new DrawFrame();

frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
setSize(600,600);
setBackground(Color.pink);
DrawComp comp = new DrawComp();
add(comp);
}
}
class DrawComp extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setStroke(new BasicStroke(10));
g2.setColor(new Color(0,128,128));
Rectangle2D rect = new
Rectangle2D.Double(200,200,40,60);
g2.fill(rect);
g2.draw(rect);
g2.rotate(100);
g2.draw(rect);
Line2D.Double line = new
Line2D.Double(100,100,200,200);
g2.draw(line);

g2.drawString("Drawing Shapes", 20,200);

Ellipse2D.Double ellipse = new


Ellipse2D.Double(100,200,70,50);
g2.draw(ellipse);
}
}
Using Color, Fonts, and Images:
• The setPaint() method of the Graphics2D class allows to
select a color for drawing operations on the graphics
context. For example,
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.RED);
g2.drawString(“Warring!”,100,100);

• We can also fill the interiors of closed shapes such as


Rectangle, Ellipses, Oval with a color.
Rectangle2D rect = new
Rectangle2D.Double(200,200,75,50);
g2.setPaint(Color.Red);
g2.fill(rect);
• You can specify a custom color by creating a Color object by
its red, green, and blue components. Using a scale of 0–255
(that is, one byte) for the redness, blueness, and greenness,
call the Color constructor like this:
– Color(int redness, int greenness, int blueness)
– g.setPaint(new Color(0, 128, 128));
– green g.drawString("Welcome!", 75, 125);
• Definition of colors is present in the Color Class. The
java.awt.Color class offers predefined constants for the
• To set the background and foreground color, use the methods
Jpanel p = new Jpanel();
p.setBackground(Color.PINK);
p.setForeground(Color.ORANGE);
SystemColor attributes:
desktop Background color of desktop
activeCaption Background color for
captions
activeCaptionText Text color for captions
activeCaptionBorder Border color for
caption text
inactiveCaption Background color for
inactive captions
inactiveCaptionText Text color for
inactive captions
inactiveCaptionBorder Border color for
inactive captions
window Background for windows
windowBorder Color of window border
frame
windowText Text color inside windows
menu Background for menus
menuText Text color for menus
text Background color for text
controlLtHighlight Light highlight color for
controls
controlHighlight Highlight color for controls
controlShadow Shadow color for
controls
controlDkShadow Dark shadow color for controls
scrollbar Background color for
scrollbars
info Background color for spot-help
• Java
text gives you predefined names for many more colors in its
SystemColor
infoText class. The constants in for
Text color thisspot-help
class encapsulate
text
the colors used for various elements of the user's system.
For example,
frame.setBackground(SystemColor.window)
RGB colors

Color(int r, int g, int b)


Parameters:
r - The red value (0–255)
g - The green value (0–255)
b - The blue value (0–255)
Using Special Fonts for Text:
• To find out which fonts are available on a particular
computer, follow the program given below:
import java.awt.*;
public class ListFonts
{
public static void main(String[] args)
{
String[] fontNames = GraphicsEnvironment

.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
for (int i = 0; i < fontNames.length; i++)

System.out.println(fontNames[i]);
}
}
• Syntax for changing the Font
Font fontObj = new Font(Font Face, Font Style,
Font size);
where Font Face – Name of the Font
Font Style – PLAIN, BOLD, ITALIC
import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
public class FontTest {
public static void main(String[] args) {
JFrame frame = new FontFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
frame.setTitle("FontTest");
frame.setSize(600, 600);
FontPanel panel = new FontPanel();
frame.add(panel);
} }
class FontPanel extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
String message = "Hello, World!";
Font f = new Font("Serif", Font.BOLD, 36);
g2.setFont(f);
g2.drawString(message, 100,200);
Font f2 = new Font("Serif",
Font.BOLD+Font.ITALIC, 36);
g2.setFont(f2);
g2.drawString(message, 200,500);
Displaying Images:
• AWT Once images are stored in local files or someplace on
the Net, you can read them into a Java application and
display them on Graphics objects. To read a graphics file
into an application, you use a Toolkit object. A Toolkit
object can read in GIF and JPEG files.
• To get a Toolkit object, use the static getDefaultToolkit
method of the Toolkit class. Here is the code to get a local
image file from the current user's directory:
– String name = "blue-ball.gif";
– Image image = Toolkit.getDefaultToolkit().getImage(name);
• To get an image file from the Net, you must supply the URL.
– URL u = new URL("http://www.someplace.com/anImage.gif");
– Image image = Toolkit.getDefaultToolkit().getImage(u);
• Now the variable image contains a reference to an object that
encapsulates the GIF file image.You can display it with the
drawImage method of the Graphics class.
public void paintComponent(Graphics g)
{
. . . g.drawImage(image, x, y, null);
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageTest
{
public static void main(String[] args)
{
ImageFrame frame = new ImageFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ImageFrame extends JFrame
{
public ImageFrame()
{
setTitle("ImageTest");
setSize(300, 600);
ImagePanel panel = new ImagePanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
class ImagePanel extends JPanel
{
private Image image;
public ImagePanel()
{
Toolkit kit = Toolkit.getDefaultToolkit();
image = kit.getImage("1.gif");
}
public void paintComponent(Graphics g)
{
g.drawImage(image, 0, 0, null);

}
}
EVENT HANDLERS:
• 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.
• Event may also occur that are not directly caused by
interactions with a user interface.
• For example, an event may be generated when a timer expires,
a counter exceeds a value, a software or hardware failure
occurs, or an operation is completed.
Event Sources
1. A source is an object that generates an event.
2. This occurs when the internal state of that object changes in
some way.
3. Sources may generate more than one type of event.
4. A source must register listeners in order for the listeners
to receive notifications
public
about
void
a specific
addTypeListener(TypeListener
type of event. e
7. Here, type is the name of the event and el is a reference to
the event listener.
8. For example the method that registers a keyboard event
listener is called addKeyListener().
9. The method that registers a mouse motion listener is called
addMouseListener().
10. When an event occurs, all registered listeners are notified
and receive a copy of the event object.
11. This known as multicasting the event. Some sources may
allow only one listener to register.
public
12. The void addTypeListener(TypeListener
general form of such method isel) throws java.util.TooManyList
this:

13. Here, Type is the name of the event and el is a reference


to the event listener.
14.When such an event occurs, the registered listener is
notified. This is known a s unicasting the event.
15. A source must also provide a method that allows a listener
public void
to unregister an interest in a removeTypeListener(TypeListener
specific type of event. el)
What is 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:
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.
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.
Event Classes
EventObject(Object src)
1. The classes that represent events are at the core of Java’s
4. Here, src is the object that generates this event.
5. EventObject contains two methods: getSource() and
toString().
6. The getSource() method returns the source of the event.
7. Its general form is shown here:
Object getSource()

8. As expected, toString() returns the string equivalent of the


event.
9. The AWTEvent, defined within the java.awt package, is a
subclass of EventObject.
10. It is the superclass of all AWT – based events used by the
delegation event model.
11. Its getID() method can
int be used to determine the type of the
getID()
event. The signature of this method is shown here:
The package java.awt.event defines several types of events that
are generated by various user interface elements.

EVENT CLASSES DESCRIPTION


ActionEvent Generated when a button is pressed, a list item is
double - clicked, or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated
ComponentEvent Generated when a component is hidden, moved, resized,
or becomes visible.
ContainerEvent Generated when a component is added to or removed from
a container.
FocusEvent Generated when a component gains or loses keyboard
focus.
InputEvent Abstract super class for all component input event
classes.
ItemEvent Generated when a check box or list item is clicked;
also occurs when a choice selection is made or a
checkable menu item is selected or deselecte.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or , released; also generated when the mouse
enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved.
Event Classes Event Listener Event Listener Interfaces Methods
Interfaces
ActionEvent ActionListener void actionPerformed(ActionEvent ae)
AdjustmentEvent AdjustmentListener void adjustmentValueChanged(AdjustmentEvent
ae)
ComponentEvent ComponentListener void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(CommonentEvent ce)
ContainerEvent ContainerListener void componentAdded(ContainerEvent ce)
void componentRemoved(ContainterEvent ce)
FocusEvent FocusListener void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
InputEvent

ItemEvent ItemListener void itemStateChanged(ItemEvent ie)

KeyEvent KeyListener Void keyPressed(KeyEvent ke)


Void keyReleased(KeyEvent ke)
Void KeyTyped(KeyEvent ke)
MouseEvent MouseListener void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseDragged(MouseEvent me)
MouseMotionListener void mouseMoved(MouseEvent me)
Event Classes Event Listener Event Listener Interfaces Methods
Interfaces
MouseWheelEvent MouseWheelListener void mouseWheelMoved(MouseWheelEvent mwe)

TextEvent TextListener void textChanged(TextEvent te)

WindowEvent WindowsListener void windowActivated(WindowEvent we)


void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

WindowFocusListener Void windowGainedFocus(WindowEvent we)


Void windowLostFocus(WindowEvent we)
Sources of Events
Event Description
Source
Button Generates action events when the button is pressed.
Checkbox Generates item event s when the check box is selected or
deselected.
Choice Generates item event s when the choice is changed.
List Generates action event s when an item is double –
clicked; generates item event when an item is selected
or deselected.
Menu Item Generates action event swhen a menu item is selected;
generates item events when a checkable menu item is
selected or deselected.
Scrollbar Generates adjustment event when the scroll bar is
manipulated.
Text Generates text events when the user enters a character.
components
Window Generated window events when a window is activated,
closed, deactivated, deiconified, iconified, opened, or
quit.
Example for ActionEvent:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ButtonText extends JFrame implements ActionListener


{

JButton b1,b2;
JTextField t1;
public ButtonText()
{
b1 = new JButton("Click");
b2 = new JButton("Display");
t1 = new JTextField(10);
Container cont = getContentPane();
cont.setLayout(new
FlowLayout(FlowLayout.CENTER));
cont.add(b1);
cont.add(b2);
cont.add(t1);
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] arg)
{
ButtonText b = new ButtonText();
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setSize(700,600);
b.setVisible(true);
b.setBackground(Color.YELLOW);

}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource().equals(b1))
t1.setText("CLICK");
else if(ae.getSource().equals(b2))
t1.setText("Display");
else
t1.setText("ERROR");
}
}
Changing Backgroung Color using ActionEvent:
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonSettingBackground extends JPanel implements
ActionListener
{
private JButton yellowButton = new JButton("Yellow");
private JButton blueButton = new JButton("Blue");
private JButton redButton = new JButton("Red");
public ButtonSettingBackground()
{
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton)
color = Color.yellow;
else if (source == blueButton)
color = Color.blue;
else if (source == redButton)
color = Color.red;
setBackground(color);
repaint();
}
public static void main(String[] args)
{
ButtonSettingBackground b = new
ButtonSettingBackground();
JFrame frame = new JFrame("ButtonTest");
frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.add(b);
frame.show();
The MouseEvent Class
• There are eight types of mouse events. The MouseEvent class
defines the following integer constants that can be used to
identify them:

MOUSE_CLICKED - The user clicked the mouse.

MOUSE_DRAGGED - The user dragged the mouse.

MOUSE_ENTERED - The mouse entered a component.

MOUSE_EXITED - The mouse exited from a compone

MOUSE_MOVED - The mouse moved.

MOUSE_PRESSED - The mouse was pressed.

MOUSE_RELEASED - The mouse was released.

MOUSE_WHEEL - The mouse wheel was moved.


MouseEvent Examples:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class MouseButton extends JFrame implements


MouseListener,MouseMotionListener
{
JButton b1;
JLabel l1;
JTextField t1;
public MouseButton()
{
l1 = new JLabel("Welcome to Mouse Event");
b1 = new JButton("Mouse Event");
t1 = new JTextField(10);
Container cont =getContentPane();
cont.setLayout(new
FlowLayout(FlowLayout.CENTER));
cont.add(l1);
cont.add(b1);
cont.add(t1);

b1.addMouseListener(this);
public static void main(String[] arg)
{
MouseButton b = new MouseButton();
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setSize(700,600);
b.setVisible(true);
b.setBackground(Color.YELLOW);

}
public void mouseClicked(MouseEvent ae)
{
t1.setText("Mouse Clicked");
}
public void mouseExited(MouseEvent ae)
{
t1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent ae)
{
t1.setText("Mouse Entered");
}
public void mousePressed(MouseEvent ae)
{
t1.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent ae)
{
t1.setText("Mouse Released");
}
public void mouseDragged(MouseEvent ae)
{
t1.setText("Mouse Dragged");
}
public void mouseMoved(MouseEvent ae)
{
t1.setText("Mouse Moved");
}

}
AWT EVENT HIERARCHY:
LAYOYUT MANAGEMENT:
• A layout manager is an object that implements
the LayoutManager interface and determines the size and
position of the components within a container.
• Although components can provide size and alignment hints, a
container's layout manager has the final say on the size and
position of the components within the container.
 GridLayout
 FlowLayout
 BorderLayout

GRIDLAYOUT:

Container cont = getContentPane();


cont.setLayout(new GridLayout(3,2);

• 3 ROWS and 2 COLUMNS


FLOWLAYOUT: ( Default Layout Manager)

Container cont = getContentPane();


cont.setLayout(new
FlowLayout(FlowLayout.CONST_VALUES);
• CONST_VALUES – LEFT, RIGHT, CENTER, LEADING, TRAILING
BORDERLAYOUT:

Container cont = getContentPane();


cont.setLayout(new
BorderLayout(BorderLayout.CONST_VALUES);
setBounds() method:
setBounds(int x,int y,int width,int height)

• You can use setBounds(x, y, width, height) to specify the


position and size of a GUI component if you set
the layout to null.
• Then (x, y) is the coordinate of the upper-left corner of
that component.
ADAPTER CLASSES:
• Many listener interfaces have more than one callback method.
• An example is MouseMotionListener that has two methods;
mouseDragged(MouseEvent event) and mouseMoved(MouseEvent
event).
• When creating a listener class that implements the interface
the Java compiler insists that all the interface methods are
implemented, which often results in many empty methods being
created to satisfy its requirements when only one or some of
its methods actually contain code.
• To avoid having many empty listener methods for many
listeners, Adapter classes are provided.
• These implement the listener interface, and provide empty
(no operation) implementation of its methods.
• The advantage is that the listener can extend these, and
only specialize methods of choice without having to provide
default implementations for the rest (these are inherited
from the Adapter).
• Adapter classes provide implementation of all methods of
interface they are implementing. Examples of adapter classes
for corresponding interfaces are:

MouseAdapter (class) => MouseListener


• It is one which contains null body definition for those
methods which are inheriting from appropriate Listener.
• In java.awt.event.* we have Listener interface called
WidowListener which contains seven abstract methods. In the
derived class implements WindowListener interface; it is
mandatory for derived class to define all the methods even
though the derived class is not required.
• If the derived class wants to define the required methods,
it has to extend its corresponding adapter class called
java.awt.event.WindowAdapter and this class contains null
body definition for WindowListener interface methods.
• Therefore which our Listener interface contains more than
one undefined method for that Listener interfaces we have
the appropriate adapter class whose general notation
is XXXAdapter.

For Example:
Listener Adapter
WindowListener
WindowAdapter
ActionListener
ActionAdapter
MouseListener
MouseAdapter Class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class AdapterMouse extends MouseAdapter
{
JFrame f;
JPanel p;
JLabel l1;
JTextField t1;
public void adapterMouse()
{
f = new JFrame();
p = new JPanel(new FlowLayout());
t1 = new JTextField(10);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(700,600);
f.setVisible(true);
l1 = new JLabel("Welcome to Mouse Event");
p.add(l1);
p.add(t1);
f.add(p);
f.addMouseListener(this);
}
public static void main(String[] arg)
{
AdapterMouse m = new AdapterMouse();
m.adapterMouse();
}
public void mousePressed(MouseEvent ae)
{
t1.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent ae)
{
t1.setText("Mouse Released");
}
}
WindowAdapter:
• The Window events can be handled using a Listener called as
WindowListener.
• When the program user tries to close a frame window, the
JFrame object is the source of a WindowEvent.
• Create an appropriate listener object and add it to the
frame’s list of window listener.
frame.addWindowListener(this);

• There are seven methods in the WindowListener Interface.

public interface WindowListener


{
void windowOpened(WindowEvent e);
void windowClosing(WindowEvent e);
void windowClosed(WindowEvent e);
void windowIconified(WindowEvent e);
void windowDeiconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeactivated(WindowEvent e);
}
• Extends the WindowAdapter Class to implement the specified
methods in your program.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class AdapterWindow extends WindowAdapter


{
JFrame f;
JPanel p;
JLabel l1;
JTextField t1;
public void adapterWindow()
{
f = new JFrame();
p = new JPanel(new FlowLayout());
t1 = new JTextField(10);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(700,600);
f.setVisible(true);
l1 = new JLabel("Welcome to Window Events");
p.add(l1);
p.add(t1);
f.add(p);
f.addWindowListener(this);
}
public static void main(String[] arg)
{
AdapterWindow m = new AdapterWindow();
m.adapterWindow();
}
public void windowOpened(WindowEvent ae)
{
t1.setText("Window Opened");
}
public void windowClosing(WindowEvent ae)
{
System.out.println("Window is Closing");
}
public void windowActivated(WindowEvent ae)
{
t1.setText("Window Activated");
}
public void windowDeactivated(WindowEvent ae)
{
System.out.println("Window is Deactivated");
}
}
SWING COMPONENTS
JLabel, JTextField, JPasswordField, JButton, JTextArea:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class TextPassword extends JFrame implements ActionListener
{

JTextField t1;
JPasswordField p1;
JButton b1;
JLabel l1,l2;
JTextArea ta;

public TextPassword()
{
Container cont = getContentPane();
cont.setLayout(new FlowLayout());
l1= new JLabel("User Name");
l2=new JLabel("Password");
ta = new JTextArea(40,40);
t1 = new JTextField(10);
p1 = new JPasswordField(10);
b1 = new JButton("CLICK");
cont.add(l1);
cont.add(t1);
cont.add(l2);
cont.add(p1);
cont.add(b1);
cont.add(ta);

b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ta.append("User Name: "+t1.getText() +
"\nPassword:
"+p1.getText()+"\n");
}
public static void main(String[] ar)
{
TextPassword tp = new TextPassword();
tp.show();
tp.setSize(500,500);

tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Labels: Labels are components that hold text. They have no
decorations and they also do not react to user input. The
constructor for a JLabel allows to specify the initial text or
icon and optionally, the alignment of the content such as
LEFT, RIGHT, CENTER, NORTH, EAST, and so on.

JLabel l1 = new JLabel(“User Name: “,


JLabel.LEFT);

JLabel Methods: javax.swing.JLabel


• JLabel (String text)
• JLabel (Icon icon)
• JLabel (String text, int align)
• JLabel (String text, Icon icon, int align) constructs a
label
• Parameters: text – The text in the Label
icon – The icon in the label
align – Alignment to LEFT(default), CENTER, RIGHT
• String getText() – gets the text of this label
• void setText(String text) – sets the text of this label
• Icon getIcon() – gets the icon of this label
• void setIcon(Icon icon) – sets the icon of this label
Choice Components: JCheckBox:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ChoiceCheck extends JFrame implements ActionListener
{
JCheckBox c1, c2,c3;
JTextArea ta;;
public ChoiceCheck()
{
c1 = new JCheckBox("Cricker");
c2 = new JCheckBox("Football");
c3 = new JCheckBox("VolleyBall");
ta= new JTextArea(40,40);
JPanel pane = new JPanel();
add(pane);
pane.add(c1);
pane.add(c2);
pane.add(c3);
pane.add(ta);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
JCheckBox ch = (JCheckBox)e.getSource();
if(ch.isSelected())
ta.append("Choices: "+ch.getText()+"\n");
else
ta.append("Unchecked:
"+ch.getText()+"\n");
}
public static void main(String args[])
{
ChoiceCheck c = new ChoiceCheck();
c.setSize(700,600);
c.show();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Choice Components: JRadioButton:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ChoiceRadio extends JFrame implements ActionListener
{
JRadioButton r1, r2;
JTextField t1;;
public ChoiceRadio()
{
ButtonGroup gr = new ButtonGroup();
r1 = new JRadioButton("Male");
r2 = new JRadioButton("Female");
gr.add(r1);
gr.add(r2);
t1 = new JTextField(10);
JPanel pane = new JPanel();
add(pane);
pane.add(r1);
pane.add(r2);
pane.add(t1);
r1.addActionListener(this);
r2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
t1.setText(e.getActionCommand());
}
public static void main(String args[])
{
ChoiceRadio c = new ChoiceRadio();
c.setSize(700,600);
c.show();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Choice Components: JComboBox:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ChoiceCombo extends JFrame implements ActionListener
{
JComboBox cb1;
JLabel l1;
public ChoiceCombo()
{
l1 = new JLabel("Select Your Choice");
cb1 = new JComboBox();
cb1.setEditable(true);
cb1.addItem("CSE");
cb1.addItem("ECE");
cb1.addItem("IT");

JPanel pane = new JPanel();


add(pane);

pane.add(l1);
pane.add(cb1);
cb1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{

JOptionPane.showMessageDialog(null,cb1.getSelectedItem()
);

//JOptionPane.showConfirmDialog(null,cb1.getSelectedItem
());
//JOptionPane.showInputDialog("Enter Value");
//JOptionPane.showOptionDialog( );
}
public static void main(String args[])
{
ChoiceCombo c = new ChoiceCombo();
c.setSize(200,200);
c.show();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Choice Components: JSlider:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

class ChoiceSlider extends JFrame implements ChangeListener


{
JSlider slide;
JLabel l1;
JTextField t1;
public ChoiceSlider()
{
slide = new
JSlider(SwingConstants.HORIZONTAL,0,100,10);
l1 = new JLabel("Select your Choice");
t1 = new JTextField(10);
JPanel pane = new JPanel();
add(pane);
pane.add(l1);
pane.add(slide);
pane.add(t1);
slide.addChangeListener(this);
}
public void stateChanged(ChangeEvent e)
{
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting())
{
int val = (int)source.getValue();
System.out.println("The Changed Value is:
"+ val);
t1.setText("Value Changed: " + val);
}
}
public static void main(String args[])
{
ChoiceSlider c = new ChoiceSlider();
c.setSize(500,500);
c.show();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JMenuBar, Jmenu:
import javax.swing.*;
import java.awt.*;
class MenuBar extends JFrame
{
JMenuBar mm;
JMenu menu1,menu2;
JTextArea t1;
public MenuBar()
{
mm = new JMenuBar();
menu1 = new JMenu("File");
menu1.add(new JMenuItem("New Ctrl+N"));
menu1.add(new JMenuItem("Open Ctrl+O"));
menu1.add(new JMenuItem("Save
Ctrl+S"));
menu1.add(new JMenuItem("Save as..."));
menu1.add(new JSeparator());
menu1.add(new JMenuItem("PageSetup..."));
menu1.add(new JMenuItem("Print...
Ctrl+P"));
menu1.add(new JSeparator());
JMenuItem exit = new JMenuItem("EXIT");
menu1.add(exit);
menu2 = new JMenu("Help");
JMenu submenu = new JMenu("About Notepad");
menu2.add(submenu);
submenu.add(new JMenuItem("History"));
submenu.add(new JMenuItem("Controls"));

mm.add(menu1);
mm.add(menu2);
setJMenuBar(mm);

t1= new JTextArea(124,124);


JPanel pane = new JPanel();
add(pane);
pane.add(t1);
}
}
MODEL – VIEW - CONTROLLER
Introduction:
• Model View Controller or MVC as it is popularly called, is a
software design pattern for developing web applications. A
Model View Controller pattern is made up of the following
three parts:
Model - The lowest level of the pattern which is responsible for
maintaining data.
View - This is responsible for displaying all or a portion of
the data to the user.
Controller - Software Code that controls the interactions
between the Model and View.
• MVC is popular as it isolates the application logic from the
user interface layer and supports separation of concerns.
• Here the Controller receives all requests for the application
and then works with the Model to prepare any data needed by
the View. The View then uses the data prepared by the
Controller to generate a final presentable response.
• The MVC abstraction can be graphically represented as follows.
The model:
• The model is responsible for managing the data of the
application. It responds to the request from the view and it
also responds to instructions from the controller to update
itself.
The view:
• A presentation of data in a particular format, triggered by a
controller's decision to present the data. They are script
based templating systems like JSP, ASP, PHP and very easy to
integrate with AJAX technology.
The controller:
• The controller is responsible for responding to user input and
perform interactions on the data model objects. The controller
receives the input, it validates the input and then performs
the business operation that modifies the state of the data
model.

FRONT CONTROLLER:
• The front controller design pattern is used to provide a
centralized request handling mechanism so that all requests
will be handled by a single handler. This handler can do the
authentication/ authorization/ logging or tracking of request
and then pass the requests to corresponding handlers.
Following are the entities of this type of design pattern.
Step 1: Create Views.
HomeView.java
public class HomeView {
public void show() {
System.out.println("Displaying Home Page");
}
}
Step 2: Create Dispatcher.
Dispatcher.java
public class Dispatcher
{
private StudentView studentView;
private HomeView homeView;
public Dispatcher()
{
studentView = new StudentView();
homeView = new HomeView();
}
public void dispatch(String request) {
if(request.equalsIgnoreCase("STUDENT"))
studentView.show();
else
homeView.show();
}
}
Step 3: Create FrontController
FrontController.java
public class FrontController {
private Dispatcher dispatcher;
public FrontController()
{
dispatcher = new Dispatcher();
}
private boolean isAuthenticUser()
{
System.out.println("User is authenticated
successfully.");
return true;
}
private void trackRequest(String request)
{
System.out.println("Page requested: " +
request);
}
public void dispatchRequest(String request)
{ //log each request
trackRequest(request);
//authenticate the user
if(isAuthenticUser())
dispatcher.dispatch(request);
Step 4: Create view StudentView: StudentView.java
public class StudentView {
public void show() {
System.out.println("Displaying Student
Page");
}
}
Step 5: Use the FrontController to demonstrate Front Controller
Design Pattern.
FrontControllerPatternDemo.java
public class FrontControllerPatternDemo
{
public static void main(String[] args)
{
FrontController frontController = new
FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
}
Step 5: Verify the output.
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
END

You might also like