0% found this document useful (0 votes)
26 views54 pages

Unit 5

Graphics programming involves working with 2D shapes, colors, fonts, and images. The Java 2D library in the Graphics2D class allows drawing shapes using classes like Line2D, Rectangle2D, and Ellipse2D located in the java.awt.geom package, which implement the Shape interface. These shapes can be drawn onto a Graphics2D object passed to a component's paintComponent method using the draw() method.
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)
26 views54 pages

Unit 5

Graphics programming involves working with 2D shapes, colors, fonts, and images. The Java 2D library in the Graphics2D class allows drawing shapes using classes like Line2D, Rectangle2D, and Ellipse2D located in the java.awt.geom package, which implement the Shape interface. These shapes can be drawn onto a Graphics2D object passed to a component's paintComponent method using the draw() method.
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/ 54

UNIT 5

EVENT DRIVEN PROGRAMMING


Graphics programming - Frame – Components - working
with 2D shapes - Using color, fonts, and images - Basics of
event handling - event handlers - adapter classes - actions
- mouse events – AWT event hierarchy - Introduction to
Swing – layout management - Swing Components –
Windows–Menus– Dialog Boxes- Study of Spring
Framework , Hibernate Framework .
EVENT DRIVEN PROGRAMMING
 Whenever you take action on a component, an event occur
 Procedural vs. Event - Driven Programming
 Procedural programming is executed in procedural order.
 In event - driven programming, code is executed upon activation of events.

Graphics programming
 Main feature in java is creating a graphical interface
 Java contains two libraries for graphics programming
1. AWT
2. SWING
1. Abstract Window ToolKit(AWT=> an API)

is a concept designed for building simple GUIs in Java applications


introduced in java1.0
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.
java.awt package consists of java awt classes which is used to create an
interactive page with buttons , text box and other tools
• GUI provides result to end user in response to
raised events. GUI is entirely based on events.
• 2. Swing

 Java Swing is a lightweight Java graphical user interface (GUI) toolkit

 is an extension of java1.1

 is a part of the Java Foundation Classes (JFC) and includes several


packages for developing rich desktop applications in Java.

 Swing includes built-in controls such as buttons, sliders, toolbars,


tables, and text

 Swing components are written entirely in Java and thus are platform-
independent
Difference between AWT and SWING

Java AWT Java Swing


stands for Abstract windows toolkit. It is an extension of AWT
require java.awt package. require javax.swing package.
AWT components are platform-dependent. Java swing components are platform-independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

Swing provides more powerful components such as


AWT provides less components than Swing.
tables, lists, scrollpanes, colorchooser etc.

AWT doesn't follows MVC(Model View


Controller) where model represents data, view
Swing follows MVC
represents presentation and controller acts as an
interface between model and view.

“Look” refers to the appearance of GUI widgets and “feel” refers to the way the widgets behave.
allowing to change the look and feel of the graphical user interface at runtime.
Frame
 is a top-level window with a title bar, menu bar, borders, and resizing corners
 subclass of Window
 The AWT library has a class called as Frame.
 The swing version is JFrame which extends Frame.
 Inheritance hierarchy for the frame and component classes in AWT and SWING
Frame
 To create simple awt example, you need a frame. There are two ways to create
a frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
 Steps to create a Frame(2 marks)
//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Create components and put them in the frame.
//...create emptyLabel...
frame. add(emptyLabel, BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);
1.Create an object of type Frame.

2.Give the Frame object a size using setSize ()


method.

3.Make the Frame object appear on the screen by


calling setVisible () method.

4.In order to close the window by clicking the


close(X) button, you will have to insert the code
for window closing event.
Java AWT Hierarchy
Components
All the elements like the button, text fields, scroll bars, etc. are called components.
In Java AWT, there are classes for each component diagram. In order to place
every component in a particular position on a screen, we need to add them to a
container.
Container

The Container is a component in AWT that can contain another components


like buttons, textfields, labels etc. The classes that extends Container class are known
as container such as Frame, Dialog and Panel.
It is basically a screen where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Components
Defn: Component is an abstract class that encapsulates all of the user
interface elements that are displayed on the screen and that interact with
the user.

 At the top of the AWT hierarchy is the Component class

A graphical user interface is developed with the help of graphical


elements like buttons, scrollbars, lists, textfields, etc. These elements
are called components.
Or
• A component is the fundamental user interface object in Java.
Everything you see on the display in a Java application is a
component(windows, panels, buttons, checkboxes, scrollbars, lists,
menus, and text fields).

 In AWT, these components are instances of the respective Component


classes.

 In Swing, components are derived from the abstract


javax.swing.JComponent class

 JComponent is the root of the Swing component hierarchy, but it


descends from the AWT Container class
 Components cannot exist alone; they are found within containers.
 Actually, containers are themselves components, thus they can be placed inside other
containers.
 In AWT, all containers are objects of class Container or one of its subtypes.
 Container objects group components, arrange them for display using a layout manager,
and associate them with a particular display device
java.awt.Component java.lang.Object
java.awt.Component
javax.swing.JComponent java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
class MyJComponent extends JComponent {

}
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
//JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the JComponent to main frame
frame.add(com);

frame.setIconImage(ImageIO.read(new File("D:/event/rose.jpg")));
frame.setVisible(true);
}
}
working with 2D shapes - Using color, fonts, and images
• Java2D library (Graphics2D class)
 is in java 1.2.
 Java 2D is an API for drawing two-dimensional graphics using the Java programming language
 Uses java.awt.Graphics2D class is subclass of Graphics class
 Organizes geometric shapes in an object oriented fashion
 A graphics object is passed to paintComponent() method which is in JComponent class[When using swing]
Syntax
public void paintComponent(Graphics g)
 e.g., to draw lines, rectangles, ellipse there are classes such as : Line2D, Rectangle2D, Ellipse2D
 these shapes classes are located in the java.awt.geom package
 These classes implements Shape interface
 To draw shapes call draw() method of the Graphics2D class
 java.awt.geom package actually provides two versions of each shape, one using coordinates of type float
and one using coordinates of type double(java1.0 draw method uses integer coordinates)
Constructors and Methods
Constructors
Class Name Syntax of constructors Description
Defines rectangle with given top-left
Rectangle2D.Double(double x, double y, double w,
Rectangle2D.Double corner, width and height double
double h) coordinates
Defines rectangle with given top-left
Rectangle2D.Float Rectangle2D.Float(float x, float y, float w, float h) corner, width and height float
coordinates
Ellipse2D.Double(double x, double y, double w, double Creates a Ellipse2D with a size of
Ellipse2D.Double
h) (Width, Height) at location (X, Y).
Line2D.Double(double x1, double y1, double x2, double Creates a Line2D from (X1, Y1) to (X2,
Line2D.Double Y2).
y2)
Methods
Class name Syntax Description
double getCenterX() , double getCenterY()
Determines center, minimum, maximum, X or Y
double getMinX() ,double getMinY()
value
double getMaxX(), double getMaxY()
RectanglerShape double getWidth(), double getHeight() Determines the width or height of the enclosing
rectangle
Returns the X or Y coordinate of the top-left corner
double getX(), double getY()
of the enclosing rectangle
Drawing on Containers
 The paintComponent() method in JComponent must be overridden
 paintComponent() is called automatically when opening, resizing, and moving window.
 Never call it explicitly.
 When we override paintComponent()the first line should be
super.paintComponent(g)which will clear the panel for drawing.
 Graphics object is passed as parameter to paintComponent() which we paint to. We
always cast the object passed to a Graphics2D which has much more functionality.
 How to tell paintComponent(Graphics g) what and how to draw?
• The method takes a java.awt.Graphics object as input.
• We encapsulate information about what/how to draw in the Graphics object.
Program that implements 2D shapes
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
class drawcomponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
g2.drawString("Implementing 2D Shapes ",100,10);
Rectangle2D r=new Rectangle2D.Double(100,100,100,75); public class SizeFrame
g2.draw(r); {
Rectangle2D r1=new Rectangle2D.Double(135,125,25,50); public static void main(String[] args)
g2.draw(r1); {
Line2D l=new Line2D.Double(100,100,150,65); JFrame frame=new JFrame("Implementing Shapes");
g2.draw(l); frame.add(new drawcomponent());
Line2D l2=new Line2D.Double(200,100,150,65); frame.setSize(500,500);
g2.draw(l2); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Ellipse2D c=new Ellipse2D.Double(145,85,10,10); // draws frame.setVisible(true);
circle }
g2.draw(c); }
}
}
Using Colors
 Painting is the process of filling the interior of the shape with a color, color gradient, or texture.
 Stroking is the process of drawing the shape's outline. You can draw an outline using different line
widths, line styles, and colors.
 Painting
 Filling the interior of a shape is a two-step process:
1. First, call a setPaint() which is in Graphics2D class . This method accepts any object that
implements the java.awt.Paint interface
2. Then call fill() method in Graphics2D class.
 Paints are immutable, which means they can't be modified after they are created.
The class java.awt.Color provides 13 standard colors as named-constants. They are: Color.RED, GREEN,
BLUE, MAGENTA, CYAN, YELLOW, BLACK, WHITE, GRAY, DARK_GRAY, LIGHT_GRAY,
ORANGE, and PINK. (In JDK 1.1, these constant names are in lowercase, e.g., red. )
 There are three types of painting supported by the 2D API. The figure contains three shapes:
• The ellipse is filled with a solid color.
• The rounded rectangle is filled with a color gradient.
 The gradient color is combination of more than one colors to design graphics.
 Object with the gradient color looks like a 3-D component.
 The object colored with gradient color makes it more attractive.
• The arc is filled with a texture
 Filling the shapes with image
 Three shapes and three paints
 Colors can be defined with Color class.
 Can specif a custom color by creating a Color object by its red,green and blue components using a scale of 0-255
 e.g., for setting custom color
g2.setPaint(new Color(0,0,255));//blue color
g2.drawString("Implementing 2D Shapes ",100,10);
Constructors and Methods

Class Syntax Description


java.awt.Color Color(int r, int g, int b) Creates a color object
java.awt.Graphics void setColor() Sets the current color
java.awt.Graphics2D void fill(Shape s) Fills the shape with the current point
java.awt.Component void setBackground(Color c) Sets the background color
void setForeground(Color c) Sets the foreground color
Working with font object
 The AWT supports multiple type fonts. Beginning with Java 2, fonts have a family name, and a face name.
 The family name is the general name of the font, such as Courier, Helvetica.
 The face name composed of family name such as “Helvetica” and optional suffix such a “Bold”. E.g.: Courier
Italic, Arial Narrow, Helvetica Bold.
 The Font class defines these variables:
Variable Meaning
String name; It stores the name of the font
int size; It stores size of the font in points
int style It stores style of the font. The possible values are: Font.PLAIN,
Font.BOLD, Font.ITALIC, and Font.BOLD+ Font.ITALIC
 Constructors of Font class : Font(String fontFace, int style, int size);
 fontFace represents name of the font,
 Style
 has possible values: Font.PLAIN, Font.BOLD, Font.ITALIC, and Font.BOLD+ Font.ITALIC.
 The combination BOLD/ITALIC represents a bold italic font. PLAIN combined with either
BOLD or ITALIC represents bold or italic, respectively.
 size determine text size in points
e.g.: Font f=new Font(“Arial Bold”,Font.BOLD+Font.ITALIC, 36);
 To use a font that is created, use setFont() to apply . This method is defined in Component.
 General form is : void setFont(Font fontObj) ; fontObj is the object that contains the desired font
e.g.: g2.setFont(f);
g2.drawString(“ Font Example ”,100,150);
Method Meaning
String getFamily(); Return the name of the font family. E.g., f.getFamily( ) will return Arial
String getName(); Both return the name of the font face. E.g., f.getName( ) will return Arial
String getFontName(); Black
int getStyle(); Return integer value that represent style of the font. The possible values are
0(Font.PLAIN),1(Font.BOLD),2(Font.ITALIC),or
3(Font.BOLD+Font.ITALIC).
int getSize(); Return the size of the current Font object
boolean isPlain(); style of the invoking Font object is Font.PLAIN, return true, otherwise false
boolean isBold(); if style of the invoking Font object is Font.BOLD, it return true, return false
boolean isItalic(); When style of the invoking Font object is Font.ITALIC, it return true, return
false
Determining the Available Fonts
 To obtain list of font in the current underlying operating system, call the
getAvailableFontFamilyNames() method defined by the GraphicsEnvironment class.
 Syntax
String[] getAvailableFontFamilyNames() ; returns an array of strings that contains the names
of the available font families.
 e.g.,
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String fnames[]=ge.getAvailableFontFamilyNames();
for(String f:fnames)
System.out.printf("\n%s",f);
Determining the Available Fonts
Another method
 getAllFonts( ) is defined by the GraphicsEnvironment class to get font name
 Syntax
Font[ ] getAllFonts( ) ; returns an array of Font objects for all of the available fonts.
E.g.,
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font fnames[]=ge.getAllFonts();
for(Font f:fnames)
System.out.printf("\n%s",f.getFontName() );
 GraphicsEnvironment reference created using getLocalGraphicsEnvironment() method, which is
defined in GraphicsEnvironment.
 Syntax is
static GraphicsEnvironment getLocalGraphicsEnvironment( )
import java.awt.*;
class font1
{
public static void main(String []a)
{
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
/*Font fnames[]=ge.getAllFonts();
for(Font f:fnames)
System.out.printf("\n%s",f.getFontName() );*/

String fnames[]=ge.getAvailableFontFamilyNames();
for(String f:fnames)
System.out.println(f);

}
}
IMAGES
 Complex Images such as potograhps can be displayed using Graphics Object.
Image Fundamentals: Loading, and Displaying
 Image class is used to refeRrto images in memory and to images that must be loaded from external
sources
 java.awt package
 Image is an abstract class, sub classed by BufferedImage and VolatileImage. Among these two,
BufferedImage is most frequently used.
Loading
 To read Image from the local file , the syntax is
Image img=ImageIO.read(new File(filename));
• e.g., image=ImageIO.read(new File("d:/event/rose.jpg"));
Display images
 to display the image, drawImage() method of Graphics Class is used
 Syntax is
boolean drawImage(Image imgob, int left, int top, int width, int height, ImageObserver imgob)
where
 img is your image object,
 x and y represent the position to draw the top-left corner of the image.
 imgob is an object that implements the ImageObserver interface. Simply specify this.
 The drawImage returns a false value if the image has not yet been completely loaded and then returns true
when the image has finally loaded.
• e.g., : g.drawImage(image,100,100,50 ,50,this) ;
 Copying an area: the image displayed can be copied to another part of the screen.
 The copyArea() method in a Graphics Class can be used for this
 syntax is: : copyArea(x, y, w, h, x-displacement, y-displacement)
 x is the x-coordinate of the area to be copied.
 y is the y-coordinate of the area to be copied.
 w is the width of the area to be copied.
 h is the height of the area to be copied.
 x-displacement is the horizontal displacement of the area to be copied.
 y-displacement is the vertical displacement of the area to be copied.
import java.awt.*;
import javax.imageio.*; Output
import javax.swing.*;
import java.io.*;
class Imageprg extends JComponent
{
private Image image;
Imageprg() throws Exception
{
image=ImageIO.read(new File("d:/rose.jpg"));
}
public void paintComponent(Graphics g)
{
g.drawImage(image,10,10,100,100,this);
g.copyArea(30, 30, 50, 70, 80, 120);// copies some portion to the new location
}
public static void main(String[] args)throws Exception
{
JFrame frame = new JFrame("Implementing Images");
frame.add(new Imageprg());
frame.setIconImage(ImageIO.read(new File("d:/rose.jpg")));
frame.setSize(500,500);
frame.setVisible(true);
}
}
Event and Listener
(Java Event Handling)
Changing the state of an object is known as an event.

For example, click on button, dragging mouse etc. The


java.awt.event package provides many event classes and Listener
interfaces for event handling.
Basics of event handling
• Event handling is fundamental concepts to create GUI-based
programs/Window based programs in java

The Event Delegation Model


• which says how events are generated and processed.
Its concept is
1. A source generates an event and sends it to one or more listeners.
2. the listener simply waits until it receives an event
3. Once received, the listener processes the event and then returns
Events
 An event is an object that describes a state change in a source.
 E.g., pressing a button , entering a character via the keyboard,
clicking the mouse
Components of Event Handling
1.Event Sources
2.Event Classes/event types.
3.Event Listeners
1. Event Sources
 Event sources are components, subclasses of java.awt.Component, capable to
generate events.

 The event source can be a button, TextField or a Frame etc.

 To process an event generated by the source, it must be registered with some


listener.

 Syntax

public void addTypeListener(TypeListener el)


• Here, Type is the name of the event and el is a reference to the event listener.
 example
 the method that registers a keyboard event listener is called addKeyListener( ).
 The method that registers a mouse motion listener is called addMouseMotionListener( )
2. Event classes/ event types.
 Source generates an event and is named by classes in java.
 For example, the event generated by button is known as
ActionEvent and that of Checkbox is known as ItemEvent.
• At the root of the Java event class hierarchy is EventObject,
which is in java.util. It is the superclass for all events.
 All the events are listed in java.awt.event package.
 EventObject contains two methods: getSource( ) and
toString( ).
 The getSource( ) method returns the source of the event.
 toString( ) returns the string equivalent of the event.

• class AWTEvent, defined within the java.awt package, is a


subclass of EventObject.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
The inheritance
diagram of AWT
event Classes
3. Event Listeners
 A listener is an object that is notified when an event occurs
 The events generated by components are handled by a special group of
interfaces known as "listeners".
 It has two major requirements.
1. First, it must be registered with one or more sources to receive events.
2. Second, it must implement methods to receive and process these
notifications.
 For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
Events
Listener
Event Class Listener Methods Class methods Generate
Interface
d by
JTextFiel
getActionComman
d, JButton
d()
ActionEvent ActionListener actionPerformed() JComboB
getModifiers()
ox

getAdjustable()
Adjustment AdjustmentList adjustmentValueChan getAdjustmentType
JScrollbar
Event ener ged() ()
getValue()
getItem()
itemStateChanged() JComboB
ItemEvent ItemListener getItmeSelectable()
ox
getStateChanged()
getKeyChar()
KeyEvent keyPressed(),keyReleas Compone
KeyListener getKeyCode()
ed() nt
getKeyText()
keyTyped()
Listener Events
Event Class Listener Methods Class methods
Interface Generated by
mouseClicked()

mouseEntered()
getX(),getY()
MouseListener mouseExited() Component
getPoint()
MouseEvent
mousePressed()

mouseReleased()
mouseDragged()
MouseMotionLi
Component
stener
mouseMoved()
WindowEve windowActivated()
nt
windowClosed()
Semantic and Low-Level Events (2 marks)
Events are classified into two types

1.Low-Level Events
 The events generated by hardware components (like MouseEvent and
KeyEvent) are known as low-level events
 Five low-level event classes are commonly used:
o KeyEvent (a key was pressed or released)
o MouseEvent (the mouse button was pressed, released, moved, or dragged)
o MouseWheelEvent (the mouse wheel was rotated)
o FocusEvent (a component got focus or lost focus)
o WindowEvent (the window state changed)
2. Semantic Events
 The events generated by software components (like Button,
List) are known as semantic events.
 E.g.,
o ActionEvent ( button click, menu selection, selecting a list
item, or ENTER typed in a text field)
o AdjustmentEvent (the user adjusted a scrollbar)
ADAPTER CLASSES
• Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.
• An adapter class provides an empty implementation of all methods in an event listener interface.
• E.g. Suppose WindowClosing Event or method from WindowListener is to be used, if adapter class is
not used then unnecessarily all the methods from WindowListener such as windowActivated(),
windowClosed(), windowClosing(), windowDeactivated(), windowDeiconified(),
windowIconified(), windowOpened() must be defined.
• The table shows adapter classes in java.awt.event and corresponding interface .
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Adapter Class is explained using WindowListener interface. Methods in WindowListener are
Method Description
public void windowActivated(WindowEvent e) is called after the window has been opened
public void windowClosed(WindowEvent e) Invoked when a window has been closed
public void windowClosing(WindowEvent e) This method is called a user clicks on the (x)
icon to close the window.
public void windowDeactivated(WindowEvent e) Invoked when a window is no longer the user's
active window
public void windowDeiconified(WindowEvent e) Invoked when a window is changed from a
minimized to a normal state.
public void windowIconified(WindowEvent e) Invoked when a window is changed from a
normal to a minimized state.
public void windowOpened(WindowEvent e) Invoked the first time a window is made visible.
or shown after it was closed?
E.g.,1 Program with WindowListener using Anonymous Inner Class
package windolistener; E.g., 2 Program with WindowAdapter using Anonymous Inner Class
import java.awt.*; package windoadpater;
import java.awt.event.*; import java.awt.*;
import javax.swing.*; import java.awt.event.*;
public class Windolistener import javax.swing.*;
{ public class Windoadpater
public static void main(String args[]) {
{ public static void main(String args[])
JFrame j = new JFrame("Implementing window Listener"); {
// implementing Anonymous Inner class JFrame j = new JFrame("Implementing windowAdapter ");
j.addWindowListener(new WindowListener() // implementing Anonymous Inner class
{ j.addWindowListener(new WindowAdapter()
// override all 7 abstract methods {
public void windowActivated(WindowEvent e) {} // invoking only windowClosing Event
public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e)
public void windowClosing(WindowEvent e) {
{ System.out.println("Window closed ");
System.out.println("Window closed "); System.exit(0);
System.exit(0); }
} }
public void windowDeactivated(WindowEvent e) {} );
public void windowDeiconified(WindowEvent e) {} j.setSize(300,300);
public void windowIconified(WindowEvent e) {} j.setVisible(true);
public void windowOpened(WindowEvent e) {} }
} }
); // closing inner class
j.setSize(300,300); D:\event>java Windoadpater
j.setVisible(true); Window closed
}}
MOUSE EVENTS
• The class which processes the MouseEvent should implement MouseListener interface or extend
MouseAdapter
• The source must register using the addMouseListener() method.
• Syntax : public interface MouseListener extends EventListener
• When the user clicks the mouse button, three listener methods are called
1. mousePressed
2. mouseRelesed
3. mouseClicked
Method Description
public void mousePressed(MouseEvent event) Invoked when a mouse button has been pressed on a component
void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a
component
void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and
released) on a component.
void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
• To get x and y-coordinate use getX() and getY() method that belongs to MouseEvent class.
• getClickCount() method is used to identify how many mouse clicks are done.
import java.awt.*;
import java.awt.event.*; public void mouseExited(MouseEvent e)
import javax.swing.*; { l.setForeground(Color.red);
l.setText("i am Exited") ; }
public class Mouseevents extends JFrame implements
MouseListener { public void mouseEntered(MouseEvent e)
JLabel l; { l.setText("I am Entered"); }
int count=0;
Mouseevents() public void mousePressed(MouseEvent e)
{ { l.setText("I am Pressed"); }
setSize(300,300);
setVisible(true); public void mouseReleased(MouseEvent e)
l=new JLabel("mouseevents"); {
add(l); l.setText("I am Released");
l.addMouseListener(this); System.out.println(e.getX() + " "+ e.getY()); }
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} public static void main(String[] args) {
public void mouseClicked(MouseEvent e) new Mouseevents();
{ }
l.setText("i am Clicked") ; }
count=count + e.getClickCount() ;
System.out.println(count);
}
Swing is not a part of JFC (Java Foundation Classes) that is used to create GUI application
True
False

You might also like