Unit - 3 Event Driven Programming
Unit - 3 Event Driven Programming
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.
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();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
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);
.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:
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:
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:
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);
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.
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.*;
mm.add(menu1);
mm.add(menu2);
setJMenuBar(mm);
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