Java Reference
In-Depth Information
Drawing Objects
After you have defined the rendering attributes, such as color and line width, and have
created the object to be drawn, you're ready to draw something in all its 2D glory.
All drawn objects use the same Graphics2D class's methods: draw() for outlines and
fill() for filled objects. These take an object as the only argument.
Drawing a Map
The next project you will create is an application that draws a simple map using 2D
drawing techniques. Enter the text of Listing 13.2 using your editor and save the file as
Map.java .
LISTING 13.2
The Full Text of Map.java
1: import java.awt.*;
2: import java.awt.geom.*;
3: import javax.swing.*;
4:
5: public class Map extends JFrame {
6: public Map() {
7: super(“Map”);
8: setSize(350, 350);
9: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10: MapPane map = new MapPane();
11: add(map);
12: setVisible(true);
13: }
14:
15: public static void main(String[] arguments) {
16: Map frame = new Map();
17: }
18:
19: }
20:
21: class MapPane extends JPanel {
22: public void paintComponent(Graphics comp) {
23: Graphics2D comp2D = (Graphics2D)comp;
24: comp2D.setColor(Color.blue);
25: comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
26: RenderingHints.VALUE_ANTIALIAS_ON);
27: Rectangle2D.Float background = new Rectangle2D.Float(
28: 0F, 0F, (float)getSize().width, (float)getSize().height);
29: comp2D.fill(background);
30: // Draw waves
31: comp2D.setColor(Color.white);
32: BasicStroke pen = new BasicStroke(2F,
33: BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
13
Search WWH ::




Custom Search