0% found this document useful (0 votes)
61 views58 pages

Unit 5-Oops

The document defines and discusses the Graphics class and JFrame class in Java. Graphics is an abstract base class that provides methods for drawing graphics and managing rendering state, and is used by GUI components to draw themselves. A JFrame is a top-level window component that can hold other components and has decorations like a title bar. It uses the Graphics class to draw its contents and child components. The document also provides examples of using Graphics methods to draw shapes on a JFrame.

Uploaded by

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

Unit 5-Oops

The document defines and discusses the Graphics class and JFrame class in Java. Graphics is an abstract base class that provides methods for drawing graphics and managing rendering state, and is used by GUI components to draw themselves. A JFrame is a top-level window component that can hold other components and has decorations like a title bar. It uses the Graphics class to draw its contents and child components. The document also provides examples of using Graphics methods to draw shapes on a JFrame.

Uploaded by

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

Definition

 Graphics class is the abstract base class for all graphics contexts that allows an
application to draw the components that are realized on various devices.
 A Graphics object encapsulates state information needed for basic rendering
operations that Java supports.

Advantages of AWT
 Less memory: GUI programs are developed and run in a limited environment.
 Fewer boot events: Since the AWT components are implemented locally by
the operating system. Majority of binary code is preloaded when the system
starts, which reduces its startup events.
 Better response: The local components are rendered by operating system.
 Mature and Stable: ablity to work properly and rarely crashes the program.

Introduction - Frames
 A frame, is an instance of the JFrame class, is a window that has decorations
like border, title and supports button components that close or iconify the
window.
 A Frame is a top-level window.
 It uses BorderLayout as default layout manager. Applications with a GUI have
at least one frame.
 public class Frame extends Window implements MenuContainer.
 Class declaration
public class Frame extendsWindow implements MenuContainer
Field / Attributes of java.awt.Frame class:
 static float BOTTOM_ALIGNMENT
o Ease-of-use constant for getAlignmentY.
 static int CROSSHAIR_CURSOR
o Deprecated. replaced by Cursor.CROSSHAIR_CURSOR.
 static int DEFAULT_CURSOR
o Deprecated. replaced by Cursor.DEFAULT_CURSOR.
 static int HAND_CURSOR
o Deprecated. replaced by Cursor.HAND_CURSOR.
 static int ICONIFIED
o This state bit indicates that frame is iconified.
 static int MAXIMIZED_BOTH
o This state bit mask indicates that frame is fully maximized i.e., both
horizontally and vertically.
 static int MAXIMIZED_HORIZ
o This state bit indicates that frame is maximized in the horizontal
direction.
 static int MAXIMIZED_VERT
o This state bit indicates that frame is maximized in the vertical direction.
 static int NORMAL
o Frame is in the "normal" state.
 static int TEXT_CURSOR
o Deprecated. replaced by Cursor.TEXT_CURSOR.
Class constructors
 Frame() - Constructs a new instance of Frame that is initially
invisible.
 Frame(GraphicsConfiguration gc) - Constructs a new, initially
invisible Frame with the specified GraphicsConfiguration.
 Frame(String title) - Constructs a new, initially invisible Frame
object with the specified title.

 Frame(String title, GraphicsConfiguration gc) - Constructs a


new, initially invisible Frame object with the specified title and a
GraphicsConfiguration.

Method & Description


 AccessibleContext getAccessibleContext() - Gets the
AccessibleContext associated with this Frame.

 int getCursorType() - Deprecated. As of JDK version 1.1,


replaced by Component.getCursor().

 int getExtendedState() - Gets the state of this frame.

 static Frame[] getFrames() - Returns an array of all Frames


created by this application.

 Image getIconImage() - Returns the image to be displayed as the


icon for this frame.

 Rectangle getMaximizedBounds() - Gets maximized bounds for


this frame.
 MenuBar getMenuBar() - Gets the menu bar for this frame.

 int getState() - Gets the state of this frame (obsolete).

 String getTitle() - Gets the title of the frame.


 boolean isResizable() - Indicates whether this frame is resizable
by the user.
 void remove(MenuComponent m) - Removes the specified
menu bar from this frame.
 void setCursor(int cursorType) - Deprecated. As of JDK version
1.1, replaced by Component.setCursor(Cursor).

 void setIconImage(Image image) - Sets the image to be


displayed as the icon for this window.
 void setMaximizedBounds(Rectangle bounds) - Sets the
maximized bounds for this frame.
 void setMenuBar(MenuBar mb) - Sets the menu bar for this
frame to the specified menu bar.

 void setResizable(boolean resizable) - Sets whether this frame is


resizable by the user.
 void setState(int state) - Sets the state of this frame.
 void setTitle(String title) - Sets the title for this frame to the
specified string.
Methods inherited
This Frame class inherits methods from the following classes:
 java.awt.Window
 java.awt.Container
 java.awt.Component
 java.lang.Object

What is frame and JFrame Java?


 JFrame is a top-level container that provides a window on the screen.
 A frame is actually a base window on which other components rely, namely the
menu bar, panels, labels, text fields, buttons, etc.
 Almost every Swing application starts with the JFrame window.
Graphics Class
 Definition: The Graphics class is the abstract super class for all graphics
contexts which allow an application to draw onto components that can be
realized on various devices, or onto off-screen images as well.
 A graphics context provides the capabilities of drawing on the screen.
 The graphics context maintains states such as the color and font used in
drawing and interacting with the operating system to perform drawing.
 In Java, painting is done using java.awt.Graphics class, that manages a graphics
context, and provides a set of device-independent methods for drawing texts,
figures and images on the screen in different platforms.
 Each operating platform will provide a subclass of Graphics to perform
drawing under that platform.

Declaration of java.awt.Graphics class:


public abstract class Graphics extends Object
Class constructors
Constructor & Description

Graphics() ()
Constructs a new Graphics object.

Components
 Graphics is an abstract class in Java AWT is used to draw or paint the
components.
 It consists of
o Various fields to hold information like components to be painted, font,
color, XOR mode, etc., and
o methods that allow drawing various shapes on GUI components.
 Graphics is an abstract class hence can’t be initialized directly.
 Objects of its child classes can be obtained in the following two ways.
1. Inside paint() or update() method
 It is passed as an argument to paint and update methods and can be accessed
inside these methods.
 paint() and update() is in Component class
void paint(Graphics g)
void update(Graphics g)

2. getGraphics() method
 This method is present in the Component class
 It can be called on any Component to get the Graphics object for the
component.
public Graphics getGraphics()
 Creates a graphics context for the component.
 This method will return null if the component is currently not displayable.
Important methods for setting the properties of Graphics context:
 void setClip(int x, int y, int width, int height)
 void setClip(Shape clip)
 void setColor(Color c)
 void setFont(Font font)
 void setPaintMode()
 void setXORMode(Color c1)
Example:
MyFrame.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyFrame extendsFrame {


public MyFrame()
{
setVisible(true);
setSize(300, 200);
addWindowListener(newWindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawRect(100, 100, 100, 50);
}

public static void main(String[] args)


{
newMyFrame();
}
}

Output:

Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyFrame extends Frame {


public MyFrame()
{
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
System.out.println("painting...");
}

public static void main(String[] args)


{
MyFrame f = newMyFrame();
Graphics g = f.getGraphics();
try{
Thread.sleep(1000);
}
catch(Exception e) {
}
System.out.println("drawing...");
g.drawRect(100, 100, 100, 50);
System.out.println("drawn...");
}
}

Paint mode vs Xor mode


 In paint mode, the new output drawn overwrites the previous one.
Therefore if the color set in the graphics object is the same as that of the
background, the object is not visible.
 In Xor mode color of the new output is obtained by XORing provided color
with background and graphics color. Therefore object is always visible
irrespective of background color.
Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyFrame extends Frame {


public MyFrame()
{
setVisible(true);
setSize(300, 200);
setBackground(Color.red);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.setXORMode(Color.black);
g.fillRect(100, 100, 100, 50);
}

public static void main(String[] args)


{
newMyFrame();
}
}

Output:
Drawing shapes using Graphics Object
Method & Description

abstract void clearRect(int x, int y, int width, int height)


Clears the specified rectangle by filling it with the background color of the current
drawing surface.

abstract void clipRect(int x, int y, int width, int height)


Intersects the current clip with the specified rectangle.

abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy.
void draw3DRect(int x, int y, int width, int height, boolean raised)
Draws a 3-D highlighted outline of the specified rectangle.

abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
void drawBytes(byte[] data, int offset, int length, int x, int y)
Draws the text given by the specified byte array, using this graphics context's current
font and color.
void drawChars(char[] data, int offset, int length, int x, int y)
Draws the text given by the specified character array, using this graphics context's
current font and color.
abstract boolean drawImage(Image img, int x, int y, int width, int height,
Color bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the
specified rectangle.
abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this
graphics context's coordinate system.

abstract void drawOval(int x, int y, int width, int height)


Draws the outline of an oval.
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates.

void drawPolygon(Polygon p)
Draws the outline of a polygon defined by the specified Polygon object.
abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
Draws a sequence of connected lines defined by arrays of x and y coordinates.
void drawRect(int x, int y, int width, int height)
Draws the outline of the specified rectangle.
abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current
color.
abstract void drawString(String str, int x, int y)
Draws the text given by the specified string, using this graphics context's current font
and color.
void fill3DRect(int x, int y, int width, int height, boolean raised)
Paints a 3-D highlighted rectangle filled with the current color.
abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.

abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)


Fills a closed polygon defined by arrays of x and y coordinates.

void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the graphics context's
current color.
abstract void fillRect(int x, int y, int width, int height)
Fills the specified rectangle.

abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Fills the specified rounded corner rectangle with the current color.
void finalize()
Disposes of this graphics context once it is no longer referenced.
abstract Shape getClip()
Gets the current clipping area.

abstract Rectangle getClipBounds()


Returns the bounding rectangle of the current clipping area.
abstract Color getColor()
Gets this graphics context's current color.
abstract Font getFont()
Gets the current font.
FontMetrics getFontMetrics()
Gets the font metrics of the current font.

abstract FontMetrics getFontMetrics(Font f)


Gets the font metrics for the specified font.
abstract void setClip(int x, int y, int width, int height)
Sets the current clip to the rectangle specified by the given coordinates.
abstract void setColor(Color c)
Sets this graphics context's current color to the specified color.

abstract void setFont(Font font)


Sets this graphics context's font to the specified font.

abstract void setPaintMode()


Sets the paint mode of this graphics context to overwrite the destination with this
graphics context's current color.
abstract void setXORMode(Color c1)
Sets the paint mode of this graphics context to alternate between this graphics
context's current color and the new specified color.

String toString()
Returns a String object representing this Graphics object's value.

AWTGraphicsDemo.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public classAWTGraphicsDemo extends Frame{


public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}

public static void main(String[] args){


AWTGraphicsDemo awtGraphicsDemo=newAWTGraphicsDemo();
awtGraphicsDemo.setVisible(true);
}

privatevoid prepareGUI(){
setSize(400,400);
addWindowListener(newWindowAdapter(){
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
Font font =new Font("Garamond",Font.PLAIN,14);
g.setFont(font);
g.drawString("Welcome to AWT",50,150);
}
}

3. Colors and Fonts


3.1 java.awt.Color

 The class java.awt.Color provides 13 standard colors as named-constants.


 They are:
o Color.RED,GREEN, BLUE,
o MAGENTA, CYAN, YELLOW,
o BLACK, WHITE, GRAY,
o DARK_GRAY, LIGHT_GRAY, ORANGE, and PINK.

 RGB values or RGBA value can also be used.


 A - stands for alpha to specify transparency(0.0f)/opaque(1.0f)
Color(int r, int g, int b); // rgb between 0 and 255
Color(float r, float g, float b); // between 0.0f and 1.0f
Color(int r, int g, int b, int alpha); // between 0 and 255
Color(float r, float g, float b, float alpha); // between 0.0f and 1.0f
Color myColor1 = new Color(123, 111, 222);
Example
JLabel label = new JLabel("Test");
label.setBackground(Color.LIGHT_GRAY);
label.setForeground(Color.RED);
 To set the color of the Graphics context g (for drawing lines, shapes, and
texts), use g.setColor(color):
g.setColor(Color.RED);
g.drawLine(10, 20, 30, 40); // in Color.RED
g.drawRect(10, 10, 40, 50); // in myColor
java.awt.Font
 The class java.awt.Font represents a specific font face, which can be used for
rendering texts.
Constructor to construct a Font
 public Font(String name, int style, int size);
o name: Family name "Monospaced", "Serif", or "SansSerif"
orFont.SERIF, Font.SANS_SERIF
o style: Font.PLAIN, Font.BOLD, Font.ITALIC or
Font.BOLD|Font.ITALIC
o size: the point size of the font (in pt) (1 inch has 72 pt).
 setFont() method - set the current font fo Graphics context g for rendering
texts.
 For example, sets the font in bold and italics.
Font myFont = new Font(Font.SERIF, Font.BOLD | Font.ITALIC, 16);
lbl.setFont(myFont);
JLabel lbl = new JLabel("Hello");
g.setFont(myFont);
g.drawString("Using the font set", 10, 50); // in myFont3
Font's Family Name vs. Font Name
 A font could have many faces (or style), e.g., plain, bold or italic. All these faces
have similar typographic design.
 The font face name, or font name for short, is the name of a particular font
face, like "Arial", "Arial Bold", "Arial Italic", "Arial Bold Italic".
 The font family name is the name of the font family that determines the
typographic design across several faces, like "Arial". For example,
java.awt.Font[family=Arial,name=Arial Bold Italic,style=plain,size=1]
Logical Font vs. Physical Font
 JDK supports these logical font family names: "Dialog", "DialogInput",
"Monospaced", "Serif", or "SansSerif". JDK 1.6 provides
these String constants: Font.DIALOG, Font.DIALOG_INPUT, Font.MONO
SPACED, Font.SERIF, Font.SANS_SERIF.
 Physical font names are actual font libraries such as "Arial", "Times New
Roman" in the system.
3.4 (Advanced) java.awt.FontMetrics
 The java.awt.FontMetrics class can be used to measure the exact width and
height of the string for a particular font face,
 so that the string can be positioned as desired (such as at the center of the
screen).
 To create a FontMetrics, use getFontMetrics() methods of the Graphics class,
public abstract FontMetrics getFontMetrics(Font f)
// Get the FontMetrics of the specified font
public abstract FontMetrics getFontMetrics()
// Get the FontMetrics of the current font
// in java.awt.FontMetrics
public int getHeight()
public int getLeading()
public int getAscent()
public int getDescent()
 The most commonly-used function for FontMetrics is to measure the width of
a given String displayed in a certain font.
public int stringWidth(String str)
// Returns the total width for showing the specified String in this Font.

What is an Event?
 Change in the state of an object is known as event i.e. event describes the
change in state of source.
 Events are generated as result of user interaction with the graphical user
interface components.
 Example:
 clicking on a button,
 moving the mouse,
 entering a character through keyboard,
 selecting an item from list,
 scrolling the page
Types of Event
 The events can be broadly classified into two categories:
1. Foreground Events
o Events that require direct interaction of user.
o It is generated as consequences of interaction with graphical
components in GUI.
o Example: clicking on a button, moving the mouse etc.
2. Background Events
o Those events that require the interaction of end user are known as
background events.
o Example: Operating system interrupts, hardware or software failure,
timer expires etc.
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 known as event handler which 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.
Delegation Event Model – Components
 Source
o It is an object on which the event occurs.
o It is responsible for providing information about the event occurred to
it's handler.
 Listener
o It is also known as event handler.
o Listener is responsible for generating response to an event.
o From implementation point of view listener is also an object.
o Listener waits until it receives an event.
o Once the event is received, listener process the event an then returns.

 In this model, Listener needs to be registered with the source object so that the
listener can receive the event notification.
 This is an efficient way of handling the event because the event notifications
are sent only to those listener that want to receive them.
Advantages
 User interface logic is completely separated from the logic that generates the
event.
 User interface element is able to delegate the processing of an event to the
separate piece of code.

Steps involved in event handling


 The User clicks the button and the event is generated.
 Now the object of concerned event class is created automatically and
information about the source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 The method gets executed and returns.
Listener
 To design a listener class it must implement listener interfaces.
 These Listener interfaces contain public abstract callback methods which must
be implemented by the listener class.
 If it does not implement any methods of predefined interfaces then the class
can not act as a listener class for a source object.
Callback Methods
 These are the methods that are provided by API provider, defined by application
programmer and invoked by application developer.
 Callback methods represents an event method. In response to an event, java
JRE will fire callback method. All such callback methods are provided in
listener interfaces.
 If a component wants its events to be listened by listener the source must
register itself to the listener.

Registering the Source With Listener


Syntax:
addTypeListener()
 where Type represents the type of event.
Example:
 For KeyEvent use addKeyListener() to register,
 For ActionEvent use addActionListener() to register.

Registration Methods
 For registering the component with the Listener, many classes provide the
registration methods.
 Example:
o Button
 public void addActionListener(ActionListener a){}
o MenuItem
 public void addActionListener(ActionListener a){}
o TextField
 public void addActionListener(ActionListener a){}
 public void addTextListener(TextListener a){}
o TextArea
 public void addTextListener(TextListener a){}
o Checkbox
 public void addItemListener(ItemListener a){}
o Choice
 public void addItemListener(ItemListener a){}
o List
 public void addActionListener(ActionListener a){}
 public void addItemListener(ItemListener a){}
Event Classes in Java
Event Class Listener Interface Description

event that indicates in component-


defined action occurred like a
ActionEvent ActionListener
button click or selecting an item
from the menu-item list.

The adjustment event is emitted


AdjustmentEvent AdjustmentListener by an Adjustable object like
Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size
changed or changed its visibility.

When a component is added to a


container (or) removed from it,
ContainerEvent ContainerListener
then this event is generated by a
container object.

These are focus-related events,


FocusEvent FocusListener which include focus, focusin,
focusout, and blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.
An event that occurs due to a
KeyEvent KeyListener sequence of keypresses on the
keyboard.

The events that occur due to the


MouseListener &
MouseEvent user interaction with the mouse
MouseMotionListener
(Pointing Device).

An event that specifies that the


MouseWheelEv
MouseWheelListener mouse wheel was rotated in a
ent
component.

An event that occurs when an


TextEvent TextListener
object’s text changes.

An event which indicates whether


WindowEvent WindowListener a window has changed its status or
not.
Note: As Interfaces contains abstract methods which need to implemented by the registered class to
handle events.
 Different interfaces consists of different methods

Listener Interface Methods

ActionListener actionPerformed()

AdjustmentListener adjustmentValueChanged()

componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()

componentAdded()
ContainerListener
componentRemoved()
Listener Interface Methods

focusGained()
FocusListener
focusLost()

ItemListener itemStateChanged()

keyTyped()
KeyListener keyPressed()
keyReleased()

mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()

mouseMoved()
MouseMotionListener
mouseDragged()

MouseWheelListener mouseWheelMoved()

TextListener textChanged()

windowActivated()
windowDeactivated()
windowOpened()
WindowListener windowClosed()
windowClosing()
windowIconified()
windowDeiconified()

Event Handling Example


import java.awt.*;
import java.awt.event.*;
Class GFGTop extends Frame implements ActionListener {
TextField textField;
GFGTop()
{
// Component Creation
textField = newTextField();
Button button = newButton("click Here");

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{
newGFGTop();
}
}
Output

After Clicking, the text field value is set to GFG!

Event Handling By Anonymous Class

import java.awt.*;
import java.awt.event.*;

class GFG3 extendsFrame {


TextField textField;

GFG3()
{
// Component Creation
textField = newTextField();
Button button = newButton("click Here");

// Registering component with listener anonymously


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
textField.setText("Anonymous");
}
});

// add Components
add(textField);
add(button);
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}

Output

Java Adapter Classes


 Java adapter classes provide the default implementation of listener interfaces.
 If the adapter class is inherited then there is no need to provide the
implementation of all the methods of listener interfaces.
 So it saves code.
 Adapter classes are defined in
o java.awt.event and
o javax.swing.event
 The Adapter classes with their listener interfaces are as follows.
java.awt.event Adapter classes
Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

What is Java Adapter Class?


 Adapter Class is a simple java class that implements an interface with only an
empty implementation.
 Suppose, there is an interface Intref which has various methods:
interface Intref{
public void m1();
public void m2();
public void m3();
:
:
:
:
public void m1000();
}
 In this interface, there are 1000 methods present and if a class implements this
there interface then the class must provide the implementation of all the 1000
methods as defined below.
class Test implements Intref{
public void m1(){
// some statements
}
public void m2(){
// some statements
}
public void m3(){
// some statements
}
:
:
:
:
public void m1000(){
// some statements
}
}
 The problem with this approach is that it increases the length of the code and
reduces readability.
 This problem is solved using the Adapter class.
 Instead of implementing the interface extend the Adapter class and provide the
implementation of required methods.
 Hence an Adapter class provide the empty implementation for each and every
method of the Intref interface.
 Use an abstract modifier while creating an Adapter class because providing an
empty implementation to the methods of an interface will be incomplete hence
it is restricted to create an object of the class.
abstract class Adapter implements Intref{
public void m1(){};
public void m2(){};
public void m3(){};
:
:
:
:
public void m1000(){};
}
 Now extend this Adapter class in the Test class and override only the required
methods.
class Test extends Adapter{
public void m1(){
System.out.println("This is m1() method.");
}
public void m80{
System.out.println("This is m80() method.");
}
}

Java MouseListener Interface


 Java MouseListener is notified whenever the state of mouse is changed.
 It is notified against MouseEvent.
 MouseListener interface is found in java.awt.event package.
Methods of MouseListener interface
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example


import java.awt.*;
import java.awt.event.*;
public class ML extends Frame implements MouseListener{
ML(){
addMouseListener(this);
Label l=new Label();
add(l);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new ML();
}
}
Output:

Using MouseAdapter
import java.awt.*;
import java.awt.event.*;
public class MA extends MouseAdapter {
MA() {
Frame f = new Frame ("Mouse Adapter");
f.addMouseListener(this);
f.setVisible (true);
}
public void mouseClicked (MouseEvent e) {
Graphics g = f.getGraphics();
g.setColor (Color.BLUE);
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MA();
}
}
Output:
AWT MouseAdapter Class
 The class MouseAdapter is an abstract (adapter) class for receiving mouse
events.
 All methods of this class are empty.
 This class is convenience class for creating listener objects.
Class declaration
Following is the declaration for java.awt.event.MouseAdapter class:
public abstract class MouseAdapter extends Object implements MouseListener,
MouseWheelListener, MouseMotionListener
Class constructors
Constructor & Description

MouseAdapter()
Class methods
void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and
released) on a component.
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then
dragged.
void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.

void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component
but no buttons have been pushed.
void mousePressed(MouseEvent e)
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 mouseWheelMoved(MouseWheelEvent e)
Invoked when the mouse wheel is rotated.
Using MouseMotionAdapter
import java.awt.*;
import java.awt.event.*;
public class MMA extends MouseMotionAdapter {
MMA() {
Frame f = new Frame ("Mouse Motion Adapter");
f.addMouseMotionListener (this);
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
public void mouseDragged (MouseEvent e) {
Graphics g = f.getGraphics();
g.setColor (Color.ORANGE);
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MMA();
} }
Output:

What is AWT event hierarchy in java?


Hierarchy events are provided for notification purposes ONLY.
The AWT will automatically handle changes to the hierarchy internally
What is the full form of AWT event?
 The Abstract Window Toolkit (AWT) supports Graphical User Interface
(GUI) programming.
 AWT features include: A set of native user interface components.
 A robust event-handling model.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.

Components
 All the elements like the button, text fields, scroll bars, etc. are called
components.
 In Java AWT, there are classes for each component.
 In order to place every component in a particular position on a screen, it needs
to be added 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 where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
 A container itself is a component, hence a container can be added inside
container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
 The window is the container that have no borders and menu bars.
 Frame, Dialog or another Window for creating a window.
 Create an instance of Window class for creating a container.
Panel
 The Panel is the container that doesn't contain title bar, border or menu bar.
 It is generic container for holding the components.
 It can have other components like button, text field etc.
 An instance of Panel class creates a container, in which the components can be
added.
Frame
 The Frame is the container that contain title bar and border and can have menu
bars.
 It can have other components like button, text field, scrollbar etc.
 Frame is most widely used container for developing an AWT application.
Useful Methods of Component Class
Method Description

public void add(Component c) Inserts a component on this


component.

public void setSize(int width,int height) Sets the size (width and height)
of the component.

public void setLayout(LayoutManager m) Defines the layout manager for


the component.

public void setVisible(boolean status) Changes the visibility of the


component, by default false.
Java AWT Example
 There are two ways to create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)

AWTExample1.java
import java.awt.*;
public class AWTExample extends Frame {
AWTExample() {
Button b = new Button("Click Me!!");
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {
AWTExample f = new AWTExample();
}
}
Java AWT Basics
 Java AWT or Abstract Window Toolkit is an API used for developing
GUI(Graphic User Interfaces) or Window-Based Applications in Java.
 Java AWT is part of the Java Foundation Classes (JFC) that provides a way to
build platform-independent graphical applications.
 Java AWT components are platform-dependent, which means they are shown
in accordance with the operating system’s view.
 AWT is heavyweight, which means that its components consume resources
from the underlying operating system (OS).
 Layout Managers: Layout Managers are responsible for arranging data in the
containers sone of the layout managers are BorderLayout, FlowLayout, etc.
 Event Handling: AWT allows the user to handle the events like mouse
clicks, key presses, etc. using event listeners and adapters.
 Graphics and Drawing: It is the feature of AWT that helps to draw shapes,
insert images and write text in the components of a Java Application.
1. Java AWT Label
Syntax of AWT Label
public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an event when
clicked on. Button Class is used for creating a labeled button that is platform-
independent.
Syntax of AWT Button
public class Button extends Component implements Accessible

Java AWT Button Class Constructors


There are two types of Button class constructors as mentioned below:
1. Button( )
 Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
 Creates a Button with String str as a label. For example if str=”Click Here”
button with show click here as the value.
3. Java AWT TextField
public class TextField extends TextComponent

TextField Class constructors


1. TextField():
Constructs a TextField component.

2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.

3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).

4. TextField(String str, int columns):


Creates a new text field(with String str in the display) with the given number of
columns (col).
4. Java AWT Checkbox
public class Checkbox extends Component implements ItemSelectable, Accessible

Checkbox Class Constructors


1. Checkbox():
Creates a checkbox with no label.

2. Checkbox(String str):
Creates a checkbox with a str label.

3. Checkbox(String str, boolean state, CheckboxGroup group):


Creates a checkbox with the str label, and sets the state in the mentioned group.

5. Java AWT CheckboxGroup


CheckboxGroup Class is used to group together a set of Checkbox.

Syntax of AWT CheckboxGroup:


public class CheckboxGroup extends Object implements Serializable

Note: CheckboxGroup enables the use of radio buttons in AWT.

6. Java AWT Choice


The object of the Choice class is used to show a popup menu of choices.

Syntax of AWT Choice:


public class Choice extends Component implements ItemSelectable, Accessible

AWT Choice Class constructor


Choice(): It creates a new choice menu.

7. Java AWT List


The object of the AWT List class represents a list of text items.

Syntax of Java AWT List:


public class List extends Component implements ItemSelectable, Accessible

AWT List Class Constructors


The List of class constructors is defined below:
1. List():
Creates a new list.

2. List(int row):
Creates lists for a given number of rows(row).

3. List(int row, Boolean Mode)


Ceates new list initialized that displays the given number of rows.

9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible

Java AWT Scrollbar Class Constructors


There are three constructor classes in Java mentioned below:
1. Scrollbar():
It Creates a new vertical Scrollbar in the Application.

2. Scrollbar(int orientation):
Creates a new vertical Scrollbar with the given orientation.

3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the
default value and [mini, maxi] as the lower and higher limit.

10. Java AWT MenuItem & Menu


 MenuItem class adds a simple labeled menu item on the menu.
 The MenuItem class allows you to create individual items that can be
added to menus.
 And Menu is a component used to create a dropdown menu that can
contain a list of MenuItem components.

Syntax of Java AWT MenuItem


public class MenuItem extends MenuComponent implements Accessible

Syntax of Java AWT Menu


public class Menu extends MenuItem implements MenuContainer, Accessible

11. Java AWT PopupMenu


 Java AWT PopupMenu is a component that is used for dynamically
popping up a menu that appears when the user right-clicks or performs any
other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible

Introduction to Java Swing


 Swing is a Java Foundation Classes [JFC] library and an extension of the
Abstract Window Toolkit [AWT].
 Swing offers much-improved functionality over AWT,
o new components and expanded components features,
o excellent event handling with drag-and-drop support.
Introduction of Java Swing
 Swing has about four times the number of User Interface [UI] components as
AWT and is part of the standard Java distribution.
 AWT has a limited implementation, not capable of providing the components
required for developing modern commercial applications.
 Swing has a Set Of API used to Design Graphical User Interfaces
 Swing is an Extension library to the AWT
 Includes New and improved Components that have been enhancing the looks
and Functionality of GUIs’
 Swing can be used to develop Standalone GUI Apps
 It Employs model/view design architecture
 Swing is more portable and more flexible than AWT
 Swing is built on top of AWT
 Swing is Entirely written in Java
 Java Swing Components are Platform-independent and are lightweight
 Swing Supports a Pluggable look and feels
 It has introduced the components like tables, lists, Scrollpanes,
Colourchooser, tabbedpane, etc
 Swing Follows MVC.
Features Of Swing Class
 Pluggable look and feel
 Uses MVC architecture
 Lightweight Components
 Platform Independent
 Advanced features such as JTable, JTabbedPane, JScollPane, etc.
Difference between AWT and Swing
Java AWT Java Swing

AWT components are platform- Java swing components are platform-


dependent. independent.

AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look Swing supports pluggable look and
and feel. feel.

AWT provides less components than Swing provides more powerful


Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.

AWT doesn't follows MVC. Swing follows MVC.

What is JFC?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes

Commonly used Methods of Component class


Method Description

public void add(Component c) add a component on another


component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the


component.

public void setVisible(boolean b) sets the visibility of the


component. It is by default false.
The MVC Connection
 In general, a visual component is a composite of three distinct aspects of
Model-View-Controller:
1. The way that the component looks when rendered on the screen(View)
2. The way such that the component reacts to the user(Controller)
3. The state information associated with the component (Model)
Example:
import java.io.*;
import javax.swing.*;
classGFG {
public static void main(String[] args)
{
JFrame frame = newJFrame();
JButton button = newJButton(" GFG WebSite Click");
frame.add(button);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setVisible(true);
}
}

Output:

Components of Swing Class


Class Description
Class Description

A Component is the Abstract base class for about the


non menu user-interface controls of SWING.
Component
Components are represents an object with a graphical
representation

A Container is a component that can container


Container
SWING Components

A JComponent is a base class for all swing UI


JComponent
Components

A JLabel is an object component for placing text in a


JLabel
container

JButton This class creates a labeled button

A JColorChooser provides a pane of controls designed


JColorChooser
to allow the user to manipulate and select a color

A JCheckBox is a graphical(GUI) component that can


JCheckBox
be in either an on-(true) or off-(false) state

The JRadioButton class is a graphical(GUI) component


JRadioButton that can be in either an on-(true) or off-(false) state. in
the group

A JList component represents the user with the


JList
scrolling list of text items

A JComboBox component is Presents the User with a


JComboBox
show up Menu of choices

A JTextField object is a text component that will allow


JTextField
for the editing of a single line of text
Class Description

A JPasswordField object it is a text component


JPasswordField
specialized for password entry

A JTextArea object is a text component that allows for


JTextArea
the editing of multiple lines of text

A ImageIcon control is an implementation of the Icon


Imagelcon
interface that paints Icons from Images

A JScrollbar control represents a scroll bar component


JScrollbar
in order to enable users to Select from range values

JOptionPane provides set of standard dialog boxes that


JOptionPane
prompt users for a value or Something

A JFileChooser it Controls represents a dialog window


JFileChooser
from which the user can select a file.

As the task progresses towards completion, the


JProgressBar progress bar displays the tasks percentage on its
completion

A JSlider this class is lets the user graphically(GUI)


JSlider select by using a value by sliding a knob within a
bounded interval.

A JSpinner this class is a single line input where the


JSpinner field that lets the user select by using a number or an
object value from an ordered sequence

What is default layout in Swing?


 The default layout manager for the content pane of a JFrame
is BorderLayout.
 For a JPanel, the default layout manager is FlowLayout.
 The default layout manager of a container can be changed using setLayout()
method.
 To remove a layout manager, pass null to the setLayout() method.

SWING - Layouts
 Layout refers to the arrangement of components within the container. i.e.,
placing the components at a particular position within the container.
Layout Manager
 The layout manager automatically positions all the components within the
container.
 If layout manager is not specified, then the components are positioned by the
default layout manager.
 It is possible to lay out the controls by hand, however, it becomes very difficult
because of the following two reasons.
o It is very tedious to handle a large number of controls within the
container.
o Usually, the width and height information of a component is not given
when we need to arrange them.
 Java provides various layout managers to position the controls.
 Properties like size, shape, and arrangement varies from one layout manager to the
other.
 When the size of the applet or the application window changes, the size, shape,
and arrangement of the components also changes in response, i.e. the layout
managers adapt to the dimensions of the appletviewer or the application
window.
 Layout manager is associated with every Container object.
 Each layout manager is an object of the class that implements the
LayoutManager interface.
Interface & Description

LayoutManager
The LayoutManager interface declares those methods which need to be
implemented by the class, whose object will act as a layout manager.
LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.
AWT Layout Manager Classes
LayoutManager & Description
BorderLayout
This layout arranges the components to fit in five regions: east, west, north,
south, and center.
CardLayout
The CardLayout object treats each component in the container as a card.
Only one card is visible at a time.
FlowLayout
The FlowLayout is the default layout. It layout the components in a
directional flow.
GridLayout
The GridLayout manages the components in the form of a rectangular grid.
GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout
aligns the component vertically, horizontally, or along their baseline without
requiring the components of the same size.
GroupLayout
The GroupLayout hierarchically groups the components in order to position
them in a Container.

BorderLayout
 The BorderLayout is used to arrange the components in five regions: north,
south, east, west, and center.
 Each region (area) may contain one component only.
 It is the default layout of a frame or window.
 The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Example
import java.awt.*;
import javax.swing.*;
public class Border
{
Border() {
JFrame f = new JFrame();
JButton b1 = new JButton("NORTH");
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("EAST");;
JButton b4 = new JButton("WEST");;
JButton b5 = new JButton("CENTER");;
f.add(b1, BorderLayout.NORTH);
f.add(b2, BorderLayout.SOUTH);
f.add(b3, BorderLayout.EAST);
f.add(b4, BorderLayout.WEST);
f.add(b5, BorderLayout.CENTER);
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
} }
Output:
Java GridLayout
 The Java GridLayout class is used to arrange the components in a rectangular
grid.
 One component is displayed in each rectangle.
Constructors of GridLayout class
 GridLayout()
o creates a grid layout with one column per component in a row.
 GridLayout(int rows, int columns)
o creates a grid layout with the given rows and columns but no gaps
between the components.
 GridLayout(int rows, int columns, int hgap, int vgap)
o creates a grid layout with the given rows and columns along with given
horizontal and vertical gaps.
Example
 The GridLayout() constructor creates only one row.
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
GridLayoutExample() {
JFrame frameObj = new JFrame();
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");

// adding buttons to the frame


frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
public static void main(String argvs[])
{
new GridLayoutExample();
} }
Output:

Java FlowLayout
 The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow).
 It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
Menu
 A menu is a group of commands located in a menubar.
 A toolbar has buttons with some common commands in the application.
 JMenuBar — implements a menu bar.
 JMenu — implements a Menu, a popup window containing JMenuItems
 JMenuItem — implements an item in a menu. It is selected by the user to
perform an action.
 JSeparator — provides a general purpose component for implementing divider
lines.
 JCheckBoxMenuItem — implements a menu that can be selected or
deselected.
 JRadioButtonMenuItem — implements a radio button menu item, used for
mutually exclusive selection.
 JPopupMenu — implements a popup menu, a small window that pops up and
displays a series of choices.
 JMenuBar, JMenu and JMenuItems are a part of Java Swing package.
 JMenuBar is an implementation of menu bar.
 JMenuBar contains one or more JMenu objects, when the JMenu objects are
selected they display a popup showing one or more JMenuItems.
 JMenu basically represents a menu.
 It contains several JMenuItem Object.
 It may also contain JMenu Objects (or submenu).
Constructors:
 JMenuBar(): Creates a new MenuBar.
 JMenu(): Creates a new Menu with no text.
 JMenu(String name): Creates a new Menu with a specified name.
Commonly used methods:
 add(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the
Menu bar.
 add(Component c) : Add component to the end of JMenu
 add(Component c, int index) : Add component to the specified index of
JMenu
 add(JMenuItem menuItem) : Adds menu item to the end of the menu.
 add(String s) : Creates a menu item with specified string and appends it to
the end of menu.
 getItem(int index) : Returns the specified menuitem at the given index
Example:
import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener{
MenuExample(){
JFrame f=new JFrame();
JMenuItem cut=new JMenuItem("cut");
JMenuItem copy=new JMenuItem("copy");
JMenuItem paste=new JMenuItem("paste");
JMenuItem selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
JMenuBar mb=new JMenuBar();
JMenu file=new JMenu("File");
JMenu edit=new JMenu("Edit");
JMenu help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
JTextArea ta=new JTextArea();
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample();
}
}
Output:

Java Swing | JDialog with examples


 JDialog is a part Java swing package.
 The main purpose of the dialog is to add components to it.
 JDialog can be customized according to user need.
An Overview of Dialogs
 Every dialog is dependent on a Frame component.
 When that Frame is destroyed, so are its dependent Dialogs.
 When the frame is iconified, its dependent Dialogs also disappear from the
screen.
 When the frame is deiconified, its dependent Dialogs return to the screen.
 A swing JDialog class inherits this behavior from the AWT Dialog class.
 A Dialog can be modal. When a modal Dialog is visible, it blocks user input to
all other windows in the program.
 JOptionPane creates JDialogs that are modal. To create a non-modal Dialog,
use the JDialog class directly.
 The JDialog class is a subclass of the AWT java.awt.Dialog class.
How to Make Dialogs
 A Dialog window is an independent sub window meant to carry temporary
notice apart from the main Swing Application Window.
 Most Dialogs present an error message or warning to a user, but Dialogs can
present images, directory trees, or just about anything compatible with the main
Swing Application that manages them.
 For convenience, several Swing component classes can directly instantiate and
display dialogs.
 To create simple, standard dialogs, you use the JOptionPane class.
 The ProgressMonitor class can put up a dialog that shows the progress of an
operation.
 Two other classes, JColorChooser and JFileChooser, also supply standard
dialogs.
 To create a custom dialog, use the JDialog class directly.
What is modal dialog vs non-modal dialog?
 Like non-modal dialogs, modal dialogs contain their tab sequence. That is, Tab
and Shift + Tab do not move focus outside the dialog. However, unlike most
non-modal dialogs, modal dialogs do not provide means for moving keyboard
focus outside the dialog window without closing the dialog.

Constructor of the class are:
 JDialog() : creates an empty dialog without any title or any specified owner
 JDialog(Frame o) :creates an empty dialog with a specified frame as its owner
 JDialog(Frame o, String s) : creates an empty dialog with a specified frame as
its owner
and a specified title
 JDialog(Window o) : creates an empty dialog with a specified window as its
owner
 JDialog(Window o, String t) : creates an empty dialog with a specified
window as its owner and specified title.
 JDialog(Dialog o) :creates an empty dialog with a specified dialog as its owner
 JDialog(Dialog o, String s) : creates an empty dialog with a specified dialog
as its owner and specified title.
Example :

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ActionListener {
public static void main(String[] args)
{
JFrame f = newJFrame("frame");
solve s = new solve();
JPanel p = new JPanel();
JButton b = new JButton("click");
b.addActionListener(s);
p.add(b);
f.add(p);
f.setSize(400, 400);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("click")) {
JDialog d = newJDialog(f, "dialog Box");
JLabel l = newJLabel("this is a dialog box");
d.add(l);
d.setSize(100, 100);
d.setVisible(true);
}
}
}

Output:
JOptionPane Features
 JOptionPane's icon allows the used to specify which icon the dialog displays.
 The user can use a custom icon, no icon at all, or any one of four
standard JOptionPane icons (question, information, warning, and error).
 Each look and feel has its own versions of the four standard icons.
Icons used by JOptionPane
Icon description Java look and feel Windows look and feel
question
information
warning
error
Creating and Showing Simple Dialogs
showMessageDialog
 Displays a modal dialog with one button, which is labeled "OK" (or the localized
equivalent).
 The message, icon, and title that the dialog displays can be specified.
//default title and icon
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.");

//custom title, warning icon


JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);

//custom title, error icon


JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane error",
JOptionPane.ERROR_MESSAGE);

//custom title, no icon


JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"A plain message",
JOptionPane.PLAIN_MESSAGE);

//custom title, custom icon


JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane custom dialog",
JOptionPane.INFORMATION_MESSAGE,
icon);
showOptionDialog
 Displays a modal dialog with the specified buttons, icons, message, title, and so on.
 With this method, the text that appears on the buttons of standard dialogs can be
changed.
//Custom button text
Object[] options = {"Yes, please",
"No, thanks",
"No eggs, no ham!"};
int n = JOptionPane.showOptionDialog(frame,
"Would you like some green eggs to go "
+ "with that ham?",
"A Silly Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,options[2]);
JOptionPane (constructor)

final JOptionPane optionPane = new JOptionPane(


"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
Component parentComponent
 The first argument to each showXxxDialog method is always the parent
component, which must be a Frame, a component inside a Frame, or null.
 If a Frame or Dialog is specifed, then the Dialog will appear over the center of the
Frame and follow the focus behavior of that Frame.
 If a component is specified inside a Frame, then the Dialog will appear over the
center of that component and will follow the focus behavior of that component's
Frame.
 If null is specified, then the look and feel will pick an appropriate position for
the dialog — generally the center of the screen
Object message
 This required argument specifies what the dialog should display in its main
area.
 Generally, specify a string, which results in the dialog displaying a label with the
specified text.
 You can split the message over several lines by putting newline (\n) characters
inside the message string. For example:
"Complete the sentence:\n \"Green eggs and...\""
String title
 The title of the dialog.
int optionType
 Specifies the set of buttons that appear at the bottom of the dialog.
 Values : DEFAULT_OPTION, YES_NO_OPTION, YES_
NO_CANCEL_OPTION, OK_CANCEL_OPTION.
int messageType
 This argument determines the icon displayed in the dialog.
 values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE,
INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_M
ESSAGE.
Icon icon
 The icon to display in the dialog.
Object[] options
 Generally used to specify the string displayed by each button at the bottom
of the dialog.
Object initialValue
Specifies the default value to be selected.
 By default, an option pane created with showMessageDialog displays the
information icon,
 If created with showConfirmDialog or showInputDialog displays the question
icon, and one created with a JOptionPane constructor displays no icon.

You might also like