Unit 5
Unit 5
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 an extension of java1.1
Swing components are written entirely in Java and thus are platform-
independent
Difference between AWT and SWING
“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.
}
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
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.
Syntax
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