Chapter 8
Chapter 8
8 Graphics Programming
Graphics Programming
User interaction with the program is of two types:
· CUI (Character User Interface): In CUI user interacts with the application
by typing characters or commands. In CUI user should remember the
commands. It is not user friendly.
· GUI (Graphical User Interface): In GUI user interacts with the
application through graphics. GUI is user friendly. GUI makes application
attractive. It is possible to simulate real object in GUI programs.
Using GUI you can learn how to write programs that size and locate windows on the
screen, display text with multiple fonts in a window, display images, and so on.
Abstract Window Toolkit
In java to write GUI programs we can use awt (Abstract Window Toolkit)
package. The package java.awt - Contains all of the classes for creating user interfaces
and for painting graphics and images as shown in the figure 8.1 shows the Java AWT
Component Class Hierarchy.
Swing was became a part of the standard library in java SE 1.2. Swing is not a
complete replacement for the AWT.
Swing is part of the Java Foundation Classes (JFC).
Draw Back
If the user interface elements look the same on all platforms, then they will look
different from the native controls and thus users will be less familiar with them.
8.2 Java Programming Paradigms
Color
Button
Font
Canvas Panel
Graphics
Object Container
Dialog
java.lang
Window
. Component Label
Frame
Scroll Bar
Text Component
Menu Bar
Menu Component
Menu Item
Border Layout
Layout Manager
Grid Layout
Event
JFrame Constructor
Constructor Description
JFrame() Constructs a new frame that is initially
invisible.
JFrame(GraphicsConfiguration gc) Creates a Frame in the specified
GraphicsConfiguration of a screen device
and a blank title.
JFrame(String title) Creates a new, initially invisible Frame
with the specified title.
JFrame(String title, GraphicsConfiguration Creates a JFrame with the specified title
gc) and the specified GraphicsConfiguration
of a screen device.
Table 8.1 JFrame Constructors
JFrame Methods
void setTitle(String title) Sets the title for this frame to the
specified string.
String getTitle() Gets the title of the frame. The title is
displayed in the frame's border.
Image getIconImage() Returns the image to be displayed as
the icon for this frame.
void setResizable(boolean resizable) Sets whether this frame is resizable by
the user.
void setMenuBar(MenuBar mb) Sets the menu bar for this frame to the
specified menu bar.
Table 8.2 JFrame Methods
8.4 Java Programming Paradigms
import javax.swing.*;
public class JFrameDemo
{
public static void main(String[] args)
{
JFrame jf=new JFrame("JFrameDemo");
jf.setSize(200,200);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.show();
}
}
Program 8.1 Creating JFrame class using object
Output
From the above output the frame size will be (200,200) in x and y axis respectively. And
the “JFrameDemo” will be deisplayed in the title bar by JFrame constructor. Next
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); will exists the window.
Graphics Programming 8.5
import javax.swing.*;
public class JFrameExtends
{
public static void main(String[] args)
{
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SimpleFrame extends JFrame
{
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
public SimpleFrame()
{
setTitle("JFrameExtends");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
Program 8.2 Creating JFrame class using extends method
Output
Most concerns Swing programmers is the content pane. When designing a frame,
you add components into the content pane, using code such as the following:
Up to Java SE 1.4, the add method of the JFrameclass was defined to throw an exception
with the message “Do not use JFrame.add(). Use JFrame.getContentPane().add()
instead.” As of Java SE 5.0, the JFrame.addmethod has given up trying to reeducate
programmers, and it simply calls add on the content pane.
frame.add(c);
In our case, we want to add a single component to the frame onto which we will
draw our message. To draw on a component, you define a class that extends JComponent
and override the paintComponent method in that class.
Graphics Programming 8.7
The paint Component method takes one parameter of type Graphics. A Graphics object
remembers a collection of settings for drawing images and text, such as the font you set
or the current color. All drawing in Java must go through a Graphics object. It has
methods that draw patterns, images, and text.
In our case, we want to draw the string "Not a Hello, World Program" in our
original window, we’ll start the string at coordinates (75, 100). This means the first
character in the string will start at a position 75 pixels to the right and 100 pixels down.
NOTE: Instead of extending JComponent, some programmers prefer to extend the JPanel
class. A JPanel is intended to be a container that can contain other components, but it is
also possible to paint on it. There is just one difference. A panel is opaque, which means
that it is responsible for painting all pixels within its bounds. The easiest way to achieve
8.8 Java Programming Paradigms
that is to paint the panel with the background color, by calling super .paintComponentin
the paint Component method of each panel subclass:
Output
To draw a shape, you first create an object of a class that implements the Shape
interface and then call the draw method of the Graphics2D class. For example:
Rectangle2D rect = . . .;
g2.draw(rect);
8.10 Java Programming Paradigms
NOTE: Before the Java 2D library appeared, programmers used methods of the
Graphics class such as drawRectangle to draw shapes.
The Java 2D shapes use floating-point coordinates. In many cases, that is a great
convenience because it allows you to specify your shapes in coordinates that are
meaningful to you (such as millimeters or inches) and then translate to pixels.
The Java programming language is adamant about requiring casts when
converting double values into float values. For example, consider the following
statement:
float f = 1.2; // Error
This statement does not compile because the constant 1.2 has type double, and the
compiler is nervous about loss of precision. The remedy is to add an F suffix to the
floating point constant:
float f = 1.2F; // Ok
Now consider this statement:
Rectangle2D r = . . .
float f = r.getWidth(); // Error
This statement does not compile either, for the same reason. The getWidth
method returns a double. This time, the remedy is to provide a cast:
float f = (float) r.getWidth(); // Ok
Because the suffixes and casts are a bit of a pain, the designers of the 2D library
decided to supply two versions of each shape class: one with float coordinates for frugal
programmers, and one with double coordinates for the lazy ones.
Rectangle2D class is an abstract class with two concrete subclasses, which are also static
inner classes: as shown in the diagram
Rectangle2D.Float
Rectangle2D.Double
Rectangle2D
Rectangle2D.Float Rectangle2D.Double
Actually, because both Rectangle 2D.Float and Rectangle 2D.Double extend the
common Rectangle 2D class and the methods in the subclasses simply override methods
in the Rectangle 2D superclass, there is no benefit in remembering the exact shape type.
You can simply use Rectangle2D variables to hold the rectangle references.
The classes Rectangle2D and Ellipse2D both inherit from the common superclass
Rectangular Shape. Admittedly, ellipses are not rectangular, but they have a bounding
rectangle .
The Rectangular Shape class defines over 20 methods that are common to these
shapes, among them such useful methods as get Width, getHeight, getCenterX, and
getCenterY(but sadly, at the time of this writing, not a get Center method that returns the
center as a Point2D object).
Finally, a couple of legacy classes from Java 1.0 have been fitted into the shape
class hierarchy.The Rectangle and Point classes, which store a rectangle and a point with
integer coordinates, extend the Rectangle2D and Point2D classes.
8.12 Java Programming Paradigms
Point2D Shape
Ellipse2D Rectangle2D
Rectangle
The figure 8.5 shows the Relationships between the shape classes. However, the Double
and Float subclasses are omitted. Legacy classes are marked with a gray fill.
Rectangle2D and Ellipse 2D objects are simple to construct. You need to specify
constructs an ellipse that is bounded by a rectangle with the top -left corner at (150,
200),width 100, and height 50.
If you isn’t the point on top-left corner, one or both of the coordinate differences
will be negative and the rectangle will come out empty. In that case, first create a blank
rectangle and use the setFrameFromDiagonal method, as follows:
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);
Or, even better, if you know the corner points as Point2D objects p and q, then
rect.setFrameFromDiagonal(p, q);
When constructing an ellipse, you usually know the center, width, and height, and
not the corner points of the bounding rectangle (which don’t even lie on the ellipse). The
setFrameFromCenter method uses the center point, but it still requires one of the four
corner points. Thus, you will usually end up constructing an ellipse as follows:
Graphics Programming 8.13
To construct a line, you supply the start and end points, either as Point2D objects or as
pairs of numbers:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
java.awt.geom.RectangularShape
doublegetCenterX()
doublegetCenterY()
doublegetMinX()
doublegetMinY()
Graphics Programming 8.15
doublegetMaxX()
doublegetMaxY()
returns the center, minimum, or maximum x- or y-value of the enclosing rectangle.
doublegetWidth()
doublegetHeight()
returns the width or height of the enclosing rectangle.
doublegetX()
double getY()
returns the x- or y-coordinate of the top-left corner of the enclosing rectangle.
java.awt.geom.Rectangle2D.Double
Rectangle2D.Double(double x, double y, double w, double h)
constructs a rectangle with the given top-left corner, width, and height.
Rectangle2D.Float(float x, float y, float w, float h)
constructs a rectangle with the given top-left corner, width, and height.
java.awt.geom.Ellipse2D.Double
Ellipse2D.Double(double x, double y, double w, double h)
constructs an ellipse whose bounding rectangle has the given top-left corner,
width, and height.
java.awt.geom.Point2D.Double
Point2D.Double(double x, double y)
constructs a point with the given coordinates.
Line2D.Double(Point2D start, Point2D end)
Line2D.Double(double startX, double startY, double endX, double endY).
constructs a line with the given start and end points.
The set Paint method of the Graphics2D class lets you select a color that is used
for all subsequent drawing operations on the graphics context. For example:
g2.setPaint(Color.RED);
g2.drawString("Warning!", 100, 100);
You can fill the interiors of closed shapes (such as rectangles or ellipses) with a color.
To draw in multiple colors, you select a color, draw or fill, then select another
color, and draw or fill again.
You define colors with the Color class. The java .awt .Colorclass offers
predefined constants for the following 13 standard colors:
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY,
MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW
You can specify a custom color by creating a Color object by its red, green, and
blue components. Using a scale of 0–255 (that is, one byte) for the redness, blueness, and
greenness, call the Color constructor like this:
Color(int redness, int greenness, int blueness)
Here is an example of setting a custom color:
g2.setPaint(new Color(0, 128, 128)); // a dull blue-green
g2.drawString("Welcome!", 75, 125);
To set the background color, you use the set Background method of the
Component class, an ancestor of JComponent.
MyComponent p = new MyComponent();
p.setBackground(Color.PINK);
There is also a set Foreground method. It specifies the default color that is used
for drawing on the component.
Java gives you predefined names for many more colors in its SystemColorclass.
The constants in this class encapsulate the colors used for various elements of the user’s
system.
For example,
p.setBackground(SystemColor.window)
will sets the background color of the component to the default used by all windows on the
user’s desktop.
The third argument is the point size. Points are commonly used in typography to
indicate the size of a font. There are 72 points per inch.
You can use a logical font name in the place of a font face name in the Font
constructor. You specify the style (plain, bold, italic, or bold italic) by setting the second
Font constructor argument to one of the following values:
Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC
The font is plain with a font size of 1 point. Use the deriveFontmethod to get a font of the
desired size:
Font f = f1.deriveFont(14.0F);
the code that displays the string “Hello, World!” in the standard sans serif font on your
system, using 14-point bold type:
Next, let’s center the string in its component rather than drawing it at an arbitrary
position. We need to know the width and height of the string in pixels. These dimensions
depend on three factors:
The font used (in our case, sans serif, bold, 14 point);
The string (in our case, “Hello, World!”); and
The device on which the font is drawn (in our case, the user’s screen).
To obtain an object that represents the font characteristics of the screen device, you
call the get Font Render Context method of the Graphics2D class. It returns an object of
the Font -Render Context class. You simply pass that object to the get String Bounds
method of the Font
class:
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = f.getStringBounds(message, context);
8.18 Java Programming Paradigms
Baseline is the imaginary line where, for example, the bottom of a character like “e”
rests.
Ascent is the distance from the baseline to the top of an ascender, which is the upper part
of a letter like “b” or “k,” or an uppercase character.
Descent is the distance from the baseline to a descender, which is the lower portion of a
letter like “p” or “g”.
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class FontTest
{
public static void main(String[] args)
{
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a text message panel
*/
class FontFrame extends JFrame
Graphics Programming 8.19
{
public FontFrame()
{
setTitle("FontTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
FontPanel panel = new FontPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
/**
A panel that shows a centered message in a box.
*/
class FontPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
If we want to load the image from local file or from internet and to store in a local
file, use the coding
The read method throws an IOExceptionif the image is not available. For now,
our sample program just catches that exception and prints a stack trace if it occurs.
Now the variable image contains a reference to an object that encapsulates the
image data. You can display the image with the draw Image method of the Graphics
class.
Graphics Programming 8.21
We first draw one copy of the image in the top-left corner and then use
thecopyAreacall to copy it into the entire window:
Output
Review Questions
Part-A
1. Explain the properties of frame.
2. What are the steps needed to show a Frame?
3. What is a JPanel object?
Part-B
1) How to create a frame with example program?
2) Write a program to display the content in the frame with explanation.
3) Write a program for drawing geometric shapes.
4) Write a program for example of text color and font.
5) Write a program to display an image.