Painting is used, when we want to change or enhance an existing widget. Or if we are creating a custom widget from scratch. To do the painting, we use the painting API provided by the Swing toolkit.
2D Vector Graphics
There are two different computer graphics. Vector and raster graphics. Raster graphics represents images as a collection of pixels. Vector graphics is the use of geometrical primitives such as points, lines, curves or polygons to represent images. These primitives are created using mathematical equations.
Both types of computer graphics have advantages and disadvantages. The advantages of vector graphics over raster are:
- smaller size
- ability to zoom indefinitely
- moving, scaling, filling or rotating does not degrade the quality of an image
Types of primitives
- points
- lines
- polylines
- polygons
- circles
- ellipses
- Splines
Points
The most simple graphics primitive is point. It is a single dot on the window. Interesingly, there is no method to draw a point in Swing. (Or I could not find it.) To draw a point, I used a drawLine() method. I used one point twice.import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.Random;
public class Points extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
for (int i=0; i<=1000; i++) {
Dimension size = getSize();
Insets insets = getInsets();
int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
Random r = new Random();
int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
g2d.drawLine(x, y, x, y);
}
}
public static void main(String[] args) {
Points points = new Points();
JFrame frame = new JFrame("Points");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(points);
frame.setSize(250, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}Here we draw the point. As I already said, we use a drawLine() method. We specify the same point twice.
Source : http://zetcode.com
No comments:
Post a Comment