- Lesson: Getting Started with Graphics
- Graphics Class in Java
- How does Graphic Class work in Java?
- 1. drawRoundRect (int a1, int b1, int width, int height, int horArc, int vertArc )
- 2. public abstract void fillRoundRect (int x,int y,int width,int height, int arcWidth,int arcHeight)
- 3. public abstract void clipRect (int x, . int y, int width, int height)
- 4. public void fill3DRect(int a1,int b1, int width,int height,boolean leveled)
- 5. public abstract void drawOval (int a,int b,int width1,int height1)
- 6. public abstract void setColor (Color)
- 7. public abstract void drawLine (int a1, int b1, int a2, int b2)
- Examples of Graphics Class in Java
- Example #1
- Example #2
- Conclusion
- Recommended Articles
Lesson: Getting Started with Graphics
The Java 2D API is powerful and complex. However, the vast majority of uses for the Java 2D API utilize a small subset of its capabilities encapsulated in the java.awt.Graphics class. This lesson covers the most common needs of applications developers. Less common needs are described later in the Advanced topics in the Java 2D API.
Most methods of the Graphics class can be divided into two basic groups:
- Draw and fill methods, enabling you to render basic shapes, text, and images
- Attributes setting methods, which affect how that drawing and filling appears
Methods such as setFont and setColor define how draw and fill methods render.
This figure illustrates how these methods relate to graphic objects:
- drawString – For drawing text
g.drawImage(img, 0, 0, width, height, 0, 0, imageWidth, imageHeight, null);
g2.draw(new Line2D.Double(0, 0, 30, 40));
Depending on your current need, you can choose one of several methods in the Graphics class based on the following criteria:
- Whether you want to render the image at the specified location in its original size or scale it to fit inside the given rectangle
- Whether you prefer to fill the transparent areas of the image with color or keep them transparent
Fill methods apply to geometric shapes and include fillArc , fillRect , fillOval , fillPolygon .
Whether you draw a line of text or an image, remember that in 2D graphics every point is determined by its x and y coordinates. All of the draw and fill methods need this information which determines where the text or image should be rendered.
For example, to draw a line, an application calls the following:
java.awt.Graphics.drawLine(int x1, int y1, int x2, int y2)
In this code (x1, y1) is the start point of the line, and (x2, y2) is the end point of the line.
So the code to draw a horizontal line is as follows:
Graphics.drawLine(20, 100, 120, 100);
The demo below accumulates all mentioned techniques. Move the slider to display various weather types.
Note: If you don’t see the applet running, you need to install at least the Java SE Development Kit (JDK) 7 release.
The WeatherWizard demo uses the JSlider component as well as various graphics capabilities to generate and display a specified weather type. For more information about the JSlider class see the How to Use Sliders section of the Swing Tutorial.
The paint method of the WeatherPainter class implements graphics features. The following code draws an image determined by using the setupWeatherReport() method.
. origComposite = g2.getComposite(); if (alpha0 != null) g2.setComposite(alpha0); g2.drawImage(img0, 0, 0, size.width, size.height, 0, 0, img0.getWidth(null), img0.getHeight(null), null); if (img1 != null) < if (alpha1 != null) g2.setComposite(alpha1); g2.drawImage(img1, 0, 0, size.width, size.height, 0, 0, img1.getWidth(null), img1.getHeight(null), null); >.
The setFont and drawString methods render the temperature and the weather condition.
. // Freezing, Cold, Cool, Warm, Hot, // Blue, Green, Yellow, Orange, Red Font font = new Font("Serif", Font.PLAIN, 36); g.setFont(font); String tempString = feels + " " + temperature+"F"; FontRenderContext frc = ((Graphics2D)g).getFontRenderContext(); . g.setColor(textColor); int xTextTemp = rX-(int)boundsTemp.getX(); int yTextTemp = rY-(int)boundsTemp.getY(); g.drawString(tempString, xTextTemp, yTextTemp); int xTextCond = rX-(int)boundsCond.getX(); int yTextCond = rY-(int)boundsCond.getY() + (int)boundsTemp.getHeight(); g.drawString(condStr, xTextCond, yTextCond);
The fillRect method allows you to draw a rectangle filled with the specified color.
. Rectangle2D boundsTemp = font.getStringBounds(tempString, frc); Rectangle2D boundsCond = font.getStringBounds(condStr, frc); int wText = Math.max((int)boundsTemp.getWidth(), (int)boundsCond.getWidth()); int hText = (int)boundsTemp.getHeight() + (int)boundsCond.getHeight(); int rX = (size.width-wText)/2; int rY = (size.height-hText)/2; g.setColor(Color.LIGHT_GRAY); g2.fillRect(rX, rY, wText, hText); .
Try to modify the WeatherWizard demo to alter the graphical content. For example, use the fillRoundRect method instead of fillRect or apply another font size in the setFont method. Find the complete code for this applet in the WeatherWizard.java file. The demo also requires the following images: weather-cloud.png , weather-rain.png , weather-snow.png , and weather-sun.png located in the images directory.
Graphics Class in Java
It is an abstract class present in java.awt package that extends the Object class of java.lang package that serves as a superclass for all graphics contexts, which allow drawing various components in an application that can be easily realized onto various devices or many real images.
Web development, programming languages, Software testing & others
Every single object of the Graphics class is a complete package of all the methods needed for the implementation of basic functions of an applet, and with this, its state contains information related to the component on which to draw, current clip, current color, XOR alternation color, font or translations of origin.
Syntax with Parameters
public abstract class Graphics extends Object
Graphics class is an abstract class; thus, we cannot make its objects; instead, we need to use one of its subclasses such as DebugGraphics, Graphics2D. And it is also a public class; it can be accessed using any of the class.
It extends the Object class in java.lang package thus extends all its functions such as clone, equals, etc.
How does Graphic Class work in Java?
Graphics class is used to draw different visualized components on the screen that is considered as a drawing board composed of the infinite number of pixels that lie between the pixels of the output device. All the coordinates that are given as arguments to the function are considered relative to the origin that has been translated before triggering the method. Below is the procedure when we give different points in any of the methods:-
- While drawing an outline of a figure, an infinitely thin path is traversed between the pixels and placed a pixel-sized pen at the bottom and right of the anchor points.
- While drawing a given rectangle, one extra row at the right and bottom edges are occupied, whereas while filling it, the same boundaries are used to fill the color that has been set using the setColor method.
- If one writes a text, the text is written above the base coordinates.
- While drawing a baseline for a text, the pixels right below the text are considered to draw the line.
All the operations that can be performed modify the pixels lying within the Shape specified and are controlled using an object of Graphics class. This region is referred to as the user clip that can only be modified using setClip and clipReact methods.
A device clip specifying the main clipping region combined with the above-described user clip defines a composite clip that defines the region for final clipping. All drawings or writings are done in the current color, in the current font, and using the current paint mode.
1. drawRoundRect (int a1, int b1, int width, int height, int horArc, int vertArc )
This function is used to create a rectangle with rounded corners where
a1 – This argument denotes the x coordinate of the rectangle’s top-left corner to be drawn.
b1 – This argument denotes the y coordinate of the rectangle’s top-left corner to be drawn.
width – This argument denotes the width of the rectangle to be drawn.
height – This argument denotes the height of the rectangle to be drawn.
horArc – This argument denotes the horizontal diameter of the arc for all the corners of the rectangle to be drawn.
vertArc – This argument denotes the vertical diameter of the arc for all the corners of the rectangle to be drawn.
The left edge = x and right edge = x+width -1
Top edge = y and bottom edge = y+height -1
2. public abstract void fillRoundRect (int x,int y,int width,int height, int arcWidth,int arcHeight)
This method is used to fill rounded corner rectangle with the color specified as the current color. Parameters interpretation is the same as given in the drawRoundRect() method.
3. public abstract void clipRect (int x, . int y, int width, int height)
This method is used to intersect the current clip with the specifications of the rectangle. In case the current clip area is null, the specified rectangle is set as the new clip that can be modified using setClip methods. These operations do not affect the outside of the clipping area.
4. public void fill3DRect(int a1,int b1, int width,int height,boolean leveled)
This method is used to paint a 3-D highlighted rectangle filled with the color specified using the setColor method. To give a 3D look to the figure, edges will be beveled to some extent and highlighted from the top left corner.
a1 –This argument denotes the x coordinate of the rectangle’s top-left corner to be drawn.
b1 -This argument denotes the y coordinate of the rectangle’s top-left corner to be drawn.
width – This argument denotes the width of the rectangle to be drawn.
height – This argument denotes the height of the rectangle to be drawn.
leveled – a boolean value, if it Is true – rectangle made will be shown as leveled above the surface; otherwise, it will be shown on the same level of the surface.
5. public abstract void drawOval (int a,int b,int width1,int height1)
This method is used to draw the empty oval in the boundaries of the rectangle whose dimensions have been specified. The area of this oval extends upto width+1 pixels and height+1 pixels.
a –This argument denotes the x coordinate of the top left corner of the oval.
b – This argument denotes the y coordinate of the top left corner of the oval.
width1 –This argument denotes the width of the oval.
height1 –This argument denotes the height of the oval.
6. public abstract void setColor (Color)
This method is used to set the current color for the graphics object. It takes the final variable as the value of color from the Color class in java.awt package. All the operations following this line will use this particular color.
7. public abstract void drawLine (int a1, int b1, int a2, int b2)
This method is used to draw a line, using the current color, between the points (a1, b1) and (a2, b2) in this graphics context’s coordinate system.
a1 –x coordinate of the starting point of the line.
b1 – y coordinate of the starting point of the line
a2 – x coordinate of the ending point of the line.
b2 – y coordinate of the ending point of the line.
Examples of Graphics Class in Java
Different examples are mentioned below:
Example #1
Let’s draw a simple applet in java
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class Demo extends Frame < public Demo()< prepareWindow(); >@Override public void paint(Graphics g) < g.setColor(Color.GRAY); Font currentFont = new Font("Berlin Sans FB Demi",Font.ITALIC, 24); g.setFont(currentFont); g.setColor(Color.BLUE); g.drawString("Welcome to Graphics Class", 100, 150); g.setColor(Color.GREEN); g.drawLine(100, 200, 400, 200); >public static void main(String[] args) < Demo awtGraphicsDemo = new Demo(); awtGraphicsDemo.setVisible(true); >private void prepareWindow() < setSize(450,400); addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); > >
Example #2
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class Demo extends Frame < public Demo()< super("Java AWT Examples"); prepareWindow(); >public static void main(String[] args) < Demo awtGraphicsDemo = new Demo(); awtGraphicsDemo.setVisible(true); >private void prepareWindow() < setSize(450,400); addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); > @Override public void paint(Graphics g) < g.setColor(Color.GRAY); Font currentFont = new Font("Berlin Sans FB Demi", Font.ITALIC, 24); g.setFont(currentFont); g.drawString("Welcome to Graphics Class", 100, 150); g.setColor(Color.magenta); g.drawRoundRect(150, 400, 100, 150, 20, 20); g.setColor(Color.CYAN); g.fillRoundRect(400, 400, 150, 120, 20,10); Font newFont1 = new Font("ALGERIAN", Font.ITALIC, 30); g.setFont(newFont1); g.setColor(Color.orange); g.fill3DRect(600, 400, 500, 120, false); g.setColor(Color.blue); g.drawString("Welcome to Graphics Class", 1000, 700); g.drawOval(600,200,400,100); g.drawLine(100, 170, 500, 170); >>
Conclusion
Graphics class provides all the basic operations required to create the visualizing objects on the screen and all information related to its state or font properties and modifying them. However, since it’s an abstract class thus, its instance cannot be created directly, thus called using its subclasses.
Recommended Articles
This is a guide to Graphics Class in Java. Here we discuss How does Graphic Classwork in Java along with the examples, syntax and, parameters. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8