Unit 5-Oops
Unit 5-Oops
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.
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;
Output:
Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
Output:
Drawing shapes using Graphics Object
Method & Description
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.
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.
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.
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.*;
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);
}
}
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.
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
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()
// add Components
add(textField);
add(button);
setVisible(true);
}
import java.awt.*;
import java.awt.event.*;
GFG3()
{
// Component Creation
textField = newTextField();
Button button = newButton("click Here");
// add Components
add(textField);
add(button);
setVisible(true);
}
Output
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
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:
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 setSize(int width,int height) Sets the size (width and height)
of the component.
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
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).
2. Checkbox(String str):
Creates a checkbox with a str label.
2. List(int row):
Creates lists for a given number of rows(row).
9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible
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.
AWT doesn't support pluggable look Swing supports pluggable look and
and feel. feel.
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
Output:
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");
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:
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.");