Java Reference
In-Depth Information
import java.util.Observable;
import java.awt.*; // For Graphics
class SketchView extends JComponent implements Observer {
public void paint(Graphics g) {
// Temporary code
Graphics2D g2D = (Graphics2D)g; // Get a Java 2D device context
g2D.setPaint(Color.RED); // Draw in red
g2D.draw3DRect(50, 50, 150, 100, true); // Draw a raised 3D rectangle
g2D.drawString("A nice 3D rectangle", 60, 100); // Draw some text
}
// Rest of the class as before...
}
If you recompile the file SketchFrame.java and run Sketcher, you can see what the paint()
method produces. You should see the window shown here.
OK, it's not your traditional meaning of 3D. In this case, the edges of the rectangle are highlighted so
that that they appear to be beveled and lift from the top left hand corner (or the coordinate origin).
How It Works
The graphics context is passed as the argument to the paint() method as type Graphics (the base
class for Graphics2D) so to use the methods defined in the Graphics2D class we must first cast it to
that type. The paint() method has a parameter type of Graphics for compatibility reasons.
Once we have cast the graphics context, we then set the color in which we will draw by calling the
setPaint() method for the Graphics2D object and passing the drawing color as an argument. All
subsequent drawing operations will now be in Color.RED . We can change this again later with another
call to setPaint() when we want to draw in a different color.
Next we call the draw3DRect() method defined in the Graphics2D class that draws a 3D rectangle.
The first two arguments are integers specifying the x and y coordinates of the top-left corner of the
rectangle to be drawn, relative to the user space origin of the component - in this case the top-left
corner of the view object in the content pane. The third and fourth arguments are the width and height
of the rectangle respectively, also in user coordinates.
Search WWH ::




Custom Search