Computer graphics with java an introduction | Razsoft Education
Graphics is a way to represent visual element in application. Java provided us rich set of methods and class through Java2D API to deal with the graphics in java platform and application. Using AWT methods to draw and manipulated GUI interface.
Java2D comes with rich set of function to manipulate images, text, font, color, etc. It has capability to draw basic geometric shapes and curves. Java media framework allows us to work with media files and create animations. Java media framework depends upon Java2D framework for rendering purposes.
For basic drawing operation every java AWT component which is visible to screen contains a reference to graphics object, which is an object of abstract class Graphics. It comes with many useful methods to draw elements like rectangle, ellipses and lines on AWT components. To use this method we just need to override paint() method of AWT component.
In this example we are going to draw a rectangle in AWT Frame.
import java.awt.*;
import java.awt.event.*;
public class Test_Frame extends Frame {
@Override
public void paint(Graphics g) {
g.drawRect(50, 50, 300, 200);
}
public static void main(String[] args) {
Test_Frame mainFrame = new Test_Frame();
mainFrame.setTitle("Rectangle demo");
mainFrame.setSize(400, 400);
mainFrame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
mainFrame.setVisible(true);
}
}
- Here we first extended the Frame class of AWT to create a frame to show our graphics.
- We then override the paint() method and get graphics instance.
- Then using drawRect() method draws a rectangle. Which draw a rectangle starting form 50, 50 and height and width is 300, 200.
- Then make an object of class to create instance of frame.
- Then set the frame title and size.
- Then write the code to close the window using event listener.
- Then make frame visible.
Here are some issues with this method of drawing.
- We can’t use a shape again and again.
- It’s very hard to manage large number of shapes.
- It’s very hard to transform the shapes.
- Can only use integer’s values to draw the shapes.
- No width and style control for stroke.
To overcome these issues we use Java2D API.
Next :- Java2D API or Graphics 2D API in java | Razsoft Education
Comments
Post a Comment