Graphics Programming with Java 2D. Java 2D API  Shapes, text, and images  A uniform mechanism for performing transformations  rotation and scaling,

Slides:



Advertisements
Similar presentations
Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.
Advertisements

Custom Painting Gestione della Grafica customizzata Vedi anche:
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Introduction to Computation and Problem Solving Class 17: Lab: The Graphics 2D API 1 Prof. Steven R. Lerman and Dr. V. Judson Harward.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Web Design & Development Lecture 19. Java Graphics 2.
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
Zhang & Liang, Computer Graphics Using Java 2D and 3D (c) 2007 Pearson Education, Inc. All rights reserved. 1 Chapter 2 2D Graphics: Basics.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
F27SB2 Programming Languages
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Java Two Dimensional Graphics with Affine Transforms
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics.
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
1 L38 Graphics and Java 2D™ (3). 2 OBJECTIVES In this chapter you will learn:  To understand graphics contexts and graphics objects.  To understand.
Zhang & Liang, Computer Graphics Using Java 2D and 3D (c) 2007 Pearson Education, Inc. All rights reserved. 1 Chapter 2 2D Graphics: Basics F The architecture.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Swing Graphics ● Empty Swing containers have no visual appearance except for a background color ● Every JComponent must have a paintComponent method that.
Web Design & Development Lecture 18. Java Graphics.
CS324e - Elements of Graphics and Visualization Java2D Graphics.
Chapter 16: Graphics. Objectives Learn about the paint() and repaint() methods Use the drawString() method to draw String s using various fonts and colors.
1 Review of COMPSCI 221  Chapters 1-11 in text  User Interfaces will be addressed as a take- home question.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
2D Graphics: Rendering Details
Chapter 15 Graphics and Java 2D™ Java How to Program, 8/e (C) 2010 Pearson Education, Inc. All rights reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction.
Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction 28.2Graphics Contexts and Graphics Objects 28.3Color Control 28.4Font Control 28.5Drawing.
 Pearson Education, Inc. All rights reserved. 1 Ch 12 Graphics and Java 2D In this chapter you will learn:  To understand graphics contexts.
Advanced User Interfaces with Java SD’98 - Session 3206 Ted Faison Faison Computing Inc.
Graphics and Java 2D. 2 Introduction Java’s graphics capabilities –Drawing 2D shapes –Controlling colors –Controlling fonts Java 2D API –More sophisticated.
Java Graphics. Review 3 kinds of elements in components API? Layout managers Events Extend vs. Implement.
Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
1 Chapter 3 2D Graphics: Rendering Details  Color spaces, paints stroke types  Affine transforms including translation, rotation, scaling, shearing,
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Merete S COLLEGEFACULTY OF ENGINEERING & SCIENCE Graphics ikt403 – Object-Oriented Software Development.
Object Oriented Programming.  Interface  Event Handling.
Introduction to Java Chapter 8 - Introduction to Java Graphics1 Chapter 8 Introduction to Java Graphics.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Graphics and Java2D Chapter Java Coordinate System Origin is in _____________ corner –Behind title bar of window X values increase to the ________.
Swing - 2 Session 13. Swing - 2 / 2 of 38 Objectives (1) Discuss trees and tables Discuss progress bars Discuss MVC architecture Describe menus.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
CS 240 Week 9. EventQueue.invokeLater In Swing, all user interface operations must occur on the “UI thread” – All components should be created on the.
Advanced Java Screen Update Techniques SD’98 - Session 4406 Ted Faison Faison Computing Inc.
Projects: not limited to spec Error checking File filters Create multiple file formats Polygons Filled shapes Etc.
GUI Programming in Java Hao Jiang Boston College April, 2009.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
Welcome To java
12 Graphics and Java 2D™.
CHAPTER Reacting to the user.
Aum Amriteshwaryai Namah
Java Graphics CS 2511.
JAVA 2 Design and programming of GUI
Java Graphics The basic rendering mechanism is the drawing system that controls when and how programs can draw on a graphics component. When a component.
12 Graphics and Java 2D™.
Chapter 49 Java 2D.
Presentation transcript:

Graphics Programming with Java 2D

Java 2D API  Shapes, text, and images  A uniform mechanism for performing transformations  rotation and scaling, on objects.  A wide array of presentation devices such as  displays and printers,  image formats and encodings,  color spaces,  rendering techniques and effects.  Comprehensive text and font handling,  color support

Rendering  The process of taking a collection of shapes, text, and images &  Figure out what colors the pixels should be on a screen or printer.  In the Java 2D API, the Graphics2D class is the rendering engine:  the Graphics2D object contains state attributes, such as color &  applies these attributes to the primitives when rendering them to various output devices.

The attributes of Graphics2D object  Paint: represents the color or pattern that the primitive will be when it is rendered.  Stroke: describes the line style of the outline of the shape  Font: the font of the text to be rendered  Rendering hint: suggests how a primitive should be rendered, such as whether a faster or more accurate algorithm should be used.  Transform: represents the mapping from user space to device space and additional graphic transforms, such as rotate and scale, to be applied to particular primitives.  Composite: defines how the overlapping parts of two graphic objects should be rendered  Clip: identifies the part of a primitive that is to be rendered

The Rendering Process

What is a rasterizer?  Takes ideal shapes and produces coverage values for each pixel.  The coverage values represent how much of each pixel is covered by the shape.  These coverage values are called alpha values.  Each pixel has its own alpha value which indicates the transparency of the pixel

Is it possible to use native rasterizer?  Java 2D does not use a native rasterizer for rendering fonts  Uses the T2K font rasterizer from Type Solutions  By allowing T2K to rasterize fonts, the Java 2D API isn't dependent on native rasterizers for the scalable outline fonts that it supports  can result in more consistent metrics display across different platforms and between on-screen and off-screen rendering

The Java 2D API classes The classes that represent predetermined shapes. Arc2D: an arc defined by a bounding rectangle, start angle, angular extent, and a closure type CubicCurve2D: a cubic parametric curve segment. Ellipse2D: an ellipse defined by a bounding rectangle. Line2D: a line segment in (x, y) coordinate space. Point2D: a location in (x,y) coordinate space. QuadCurve2D: a quadratic parametric curve segment. Rectangle2D: a rectangle defined by a location (x, y) and dimension (w x h) RoundRectangle2D: a rectangle with rounded corners defined by a location (x, y), a dimension (w x h), and the width and height of the corner arc.

Defining odd shapes Two classes allow us to to define odd shapes  GeneralPath  Shapes must be created segment by segment,  We can combine straight lines and curved lines into a single shape.  Area  Supports constructive area geometry  allows us to combine two shapes to create another shape, by adding or intersecting the shapes, subtracting one shape from another by subtracting the intersection of the shapes.

Complex Shapes from Geometry Primitives  Constructive Area Geometry (CAG) is the process of creating new geometric shapes by performing boolean operations on existing ones.  A special type of Shape called an Area supports boolean operations.  We can construct an Area from any Shape.

Areas examples Areas support the following boolean operations: Union Subtraction Intersection Exclusive-or (XOR)

package untitled71; import javax.swing.UIManager; import java.awt.*; import java.awt.event.*; import java.awt.font.*; import java.awt.geom.*; import javax.swing.*; // This applet renders a pear, using CAG methods: add, intersect, and subtract. public class Pear extends JApplet { Ellipse2D.Double circle, oval, leaf, stem; Area circ, ov, leaf1, leaf2, st1, st2; public void init() { circle = new Ellipse2D.Double(); oval = new Ellipse2D.Double(); leaf = new Ellipse2D.Double(); stem = new Ellipse2D.Double(); circ = new Area(circle); ov = new Area(oval); leaf1 = new Area(leaf); leaf2 = new Area (leaf); st1 = new Area (stem); st2 = new Area (stem); setBackground (Color.white); }

public void paint (Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = getSize() int w = d.width; int h = d.height; double ew = w/2; double eh = h/2; g2.setColor(Color.green); // Creates the first leaf by filling the intersection of two Area objects created from an ellipse. leaf.setFrame(ew-16, eh-29, 15.0, 15.0); leaf1 = new Area (leaf); leaf.setFrame(ew-14, eh-47, 30.0, 30.0); leaf2 = new Area (leaf); leaf1.intersect (leaf2); g2.fill(leaf1); // Creates the second leaf. leaf.setFrame (ew+1, eh-29, 15.0, 15.0); leaf1 = new Area (leaf); leaf2.intersect (leaf1); g2.fill(leaf2);

g2.setColor(Color.black); /** Creates the stem by filling the Area resulting from the subtraction of two Area objects created from an ellipse.**/ stem.setFrame (ew, eh-42, 40.0, 40.0); st1 = new Area (stem); stem.setFrame(ew+3, eh-47, 50.0, 50.0); st2 = new Area (stem); st1.subtract( st2); g2.fill(st1); g2.setColor(Color.yellow); / ** Creates the pear itself by filling the Area resulting from the union of two Area objects created by two different ellipses **/ circle.setFrame(ew-25, eh, 50.0, 50.0); oval.setFrame(ew-19, eh-20, 40.0, 70.0); circ = new Area (circle); ov = new Area (oval); circ.add(ov); g2.fill(circ); }

public static void main (String s[]) { JFrame f = new JFrame ("Pear"); f.addWindowListener (new WindowAdapter() { public void windowClosing (WindowEvent e) { System.exit(0);} } ) ; JApplet applet = new Pear(); f.getContentPane(). add ("Center", applet); applet.init(); f.pack(); f.setSize (new Dimension(150,200)); f.show(); }

java.awt.font.* Class Diagrams  Font Interfaces: MultipleMaster, OpenType Classes: java.awt.Font, FontRenderContext, LineMetrics, java.awt.FontMetrics  TextLayout Classes: TextHitInfo, TextLayout, TextLayout.CaretPolicy, LineBreakMeasurer, TextMeasurer  Attribute Classes: java.text.AttributedCharacterIterator.Attribute, GraphicAttribute, ImageGraphicAttribute, TextAttribute, ShapeGraphicAttribute, NumericShaper, TransformAttribute  Glyph Classes: GlyphMetrics, GlyphVector, GlyphJustificationInfo

java.awt.geom.* Class Diagrams  Shapes Interfaces: java.awt.Shape  Lines Interfaces: java.awt.Shape Classes: QuadCurve2D, QuadCurve2D.Double, QuadCurve2D.Float, CubicCurve2D, Line2D, CubicCurve2D.Double, Line2D.Double, CubicCurve2D.Float, Line2D.Float  Rects Interfaces: java.awt.Shape Classes: RectangularShape, RoundRectangle2D.Float, RoundRectangle2D, RoundRectangle2D.Double, Ellipse2D.Double, Rectangle2D, Ellipse2D, Ellipse2D.Float, Arc2D, Arc2D.Float, java.awt.Rectangle, Rectangle2D.Float, Rectangle2D.Double, Arc2D.Double

java.awt.geom.* Class Diagrams cont’d  Asym Interfaces: java.awt.Shape Classes: GeneralPath, Area, java.awt.Polygon  Point Classes: Point2D, Dimension2D, java.awt.Insets, java.awt.Dimension, java.awt.Point, Point2D.Float, Point2D.Double  Misc Interfaces: PathIterator Classes: AffineTransform, FlatteningPathIterator

java.awt.event.* Class Diagrams  Listener Interfaces: java.util.EventListener, AWTEventListener, ActionListener, KeyListener, AdjustmentListener, ComponentListener, MouseWheelListener, ContainerListener, MouseListener, FocusListener, MouseMotionListener, HierarchyBoundsListener, WindowStateListener, HierarchyListener, WindowFocusListener, InputMethodListener, WindowListener, ItemListener, TextListener Classes: java.util.EventListenerProxy, AWTEventListenerProxy, KeyAdapter, ComponentAdapter, ContainerAdapter, MouseAdapter, FocusAdapter, MouseMotionAdapter, HierarchyBoundsAdapter, WindowAdapter  Events Interfaces: java.awt.ActiveEvent Classes: InputMethodEvent, java.awt.AWTEvent, java.util.EventObject, HierarchyEvent, InvocationEvent, TextEvent, ActionEvent, ItemEvent, AdjustmentEvent, ComponentEvent, PaintEvent, FocusEvent, InputEvent, WindowEvent, ContainerEvent, MouseEvent, KeyEvent, MouseWheelEvent, java.awt.AWTKeyStroke, javax.swing.KeyStroke

java.awt.event.* Class Diagram cont’d  Support ventSupport.html Classes: java.awt.AWTEventMulticaster, java.awt.EventQueue

javax.swing.* Class Diagrams  Components  Hierarchy  JComponent  Labels  Slider+Progress  Spinner  CellEditor  CellRenderer  Container  RootpaneContainer  Panes  Scrolling  Layers Classes: javax.swing.JComponent

javax.swing.* Class Diagrams cont’d  Container  RootpaneContainer  Panes  Scrolling  Layers  Dialogs  JOptionPane  JFileChooser  JColorChooser

javax.swing.* Class Diagrams cont’d  Button+Menu  Buttons  ButtonModel  MenuSupport  MenuEvents  Lists  List+Combo  ListModel  ListEvent  Lists  List+Combo  ListModel  ListEvent

javax.swing.* Class Diagrams cont’d  Action  LookAndFeel  Utilities  Exceptions  javax.swing.border  javax.swing.event  Listener  Events  javax.swing.plaf  ComponentUI  UIResource  javax.swing.table  JTable  TableModel  Support  Events

javax.swing.* Class Diagrams cont’d  javax.swing.text  TextComponents  Formatter  Document  EditorKit  AttributeSet  View  Element  Position  Caret  AbstractWriter  Utilities  Events

javax.swing.* Class Diagrams cont’d  javax.swing.text.html  HTMLDocument  HTMLEditorKit  StyleSheet  Views  HTML  Parsing  javax.swing.text.html.parser  javax.swing.tree  JTree  TreeModel  TreeNode  Events  javax.swing.undo

General Approach to JAVA 2D API  Transition from the Graphics object to a Graphics2D object public void paintComponent(Graphics g) { super.paintComponent(g); // Typical Swing approach Graphics2D g2d = (Graphics2D)g; g2d.doSomeWork(...);... }  Create a Shape object Rectangle2D.Double rect =...; Ellipse2D.Double ellipse =...; Polygon poly =...; GeneralPath path =...; SomeShapeYouDefined shape =...; // Satisfies Shape interface...

General Approach to JAVA 2D API cont’d  Optional: modify drawing parameters g2d.setPaint (fillColorOrPattern); g2d.setStroke (penThicknessOrPattern); g2d.setComposite (someAlphaComposite); g2d.setFont(someFont); g2d.translate(...); g2d.rotate(...); g2d.scale(...); g2d.shear(...); g2d.setTransform(someAffineTransform);  Draw an outlined or solid version of the Shape g2d.draw(someShape); g2d.fill(someShape);

Example: Drawing Shapes import javax.swing.*; // For JPanel import java.awt.*; // For Graphics import java.awt.geom.*; // For Ellipse2D public class ShapeExample extends JPanel { private Ellipse2D.Double circle = new Ellipse2D.Double(10, 10, 350, 350); private Rectangle2D.Double square = new Rectangle2D.Double(10, 10, 350, 350); public void paintComponent(Graphics g) { clear(g); Graphics2D g2d = (Graphics2D) g; g2d.fill(circle); g2d.draw(square); } // super.paintComponent clears offscreen pixmap, we're using double buffering by default protected void clear (Graphics g) { super.paintComponent(g); } protected Ellipse2D.Double getCircle() { return(circle); } public static void main(String[] args) { WindowUtilities.openInJFrame(new ShapeExample(), 380, 400); } }

WindowUtilities.java Utility class that simplifies creating a window and setting the look and feel. import javax.swing.* ; import java.awt.*; public class WindowUtilities { /** Tell system to use native look and feel, as in previous * releases. Metal (Java) LAF is the default otherwise. **/ public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.out.println ("Error setting native LAF: " + e); } /** A simplified way to see a JPanel or other Container. * Pops up a JFrame with specified Container as the content pane. */ public static JFrame openInJFrame (Container content, int width, int height, String title, Color bgColor) { JFrame frame = new JFrame (title);

frame.setBackground (bgColor); content.setBackground (bgColor); frame.setSize (width, height); frame.setContentPane (content); frame.addWindowListener (new ExitListener()); frame.setVisible(true); return(frame); } /** Uses Color.white as the background color. public static JFrame openInJFrame(Container content, int width, int height, String title) { return(openInJFrame(content, width, height, title, Color.white)); } /** Uses Color. white as the background color, and the * name of the Container's class as the JFrame title. */ public static JFrame openInJFrame(Container content, int width, int height) { return(openInJFrame(content, width, height,content.getClass().getName(), Color.white)); } }

ExitListener.java A WindowListener with support to close the window import java.awt.*; import java.awt.event.*; public class ExitListener extends WindowAdapter { public void windowClosing (WindowEvent event) { System.exit(0); }

Paint attribute of the Graphics2D Filling a Shape  A Color (solid color): Color.red, Color.yellow  A GradientPaint (gradient fill gradually combining two colors) Constructors takes two points, two colors, and optionally a boolean flag that indicates that the color pattern should cycle.  A TexturePaint (tiled image), or  A new version of Paint that we write ourselves  Use setPaint and getPaint to change and retrieve the Paint settings.  setPaint and getPaint supersede the setColor and getColor methods in Graphics.

Example: Gradient Fills import java.awt.*; public class GradientPaintExample extends ShapeExample { // Red at (0,0), yellow at (175,175), changes gradually between. private GradientPaint gradient = new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow, true); // true means to repeat pattern public void paintComponent(Graphics g) { clear(g); Graphics2D g2d = (Graphics2D)g; drawGradientCircle(g2d); } protected void drawGradientCircle (Graphics2D g2d) { g2d.setPaint(gradient); g2d.fill(getCircle()); g2d.setPaint(Color.black); g2d.draw(getCircle()); } public static void main(String[] args) { WindowUtilities.openInJFrame(new GradientPaintExample(), 380, 400); } }

Stroke Attributes Each of the shapes drawn by the applet is constructed from one of the geometries and is then rendered through Graphics2D. The rectHeight and rectWidth variables define the dimensions of the space where each shape is drawn, in pixels. The x and y variables change for each shape so that they are drawn in a grid formation. //draw Line2D.Double g2.draw (new Line2D.Double(x, y+rectHeight-1, x + rectWidth, y)); g2.drawString("Line2D", x, stringY); // draw Rectangle2D.Double g2.setStroke(stroke); g2.draw(new Rectangle2D.Double(x, y, rectWidth, rectHeight)); g2.drawString("Rectangle2D", x, stringY); // draw RoundRectangle2D.Double g2.setStroke(dashed); g2.draw(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10) g2.drawString("RoundRectangle2D", x, stringY);

Stroke Attributes cont’d // draw Arc2D.Double g2.setStroke(wideStroke); g2.draw(new Arc2D.Double(x, y, rectWidth, rectHeight, 90, 135, Arc2D.OPEN)); // draw Ellipse2D.Double g2.setStroke(stroke); g2.draw (new Ellipse2D.Double(x, y, rectWidth, rectHeight));

Drawing GeneralPath (polygon) int x1Points[] = {x, x+rectWidth, x, x+rectWidth}; int y1Points[] = {y, y+rectHeight, y+rectHeight, y}; GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD, x1Points.length); polygon.moveTo(x1Points[0], y1Points[0]); for (int index = 1; index < x1Points.length; index++) { polygon.lineTo(x1Points[index], y1Points[index]); }; polygon.closePath(); g2.draw(polygon);

Drawing GeneralPath (polyline) int x2Points[] = {x, x+rectWidth, x, x+rectWidth}; int y2Points[] = {y, y+rectHeight, y+rectHeight, y}; GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, x2Points.length); polyline.moveTo (x2Points[0], y2Points[0]); for (int index = 1; index < x2Points.length; index++) { polyline.lineTo(x2Points[index], y2Points[index]); }; g2.draw(polyline);

Stroke Attributes cont’d // fill Rectangle2D.Double (red) g2.setPaint(red); g2.fill(new Rectangle2D.Double(x, y, rectWidth,rectHeight)); // fill RoundRectangle2D.Double g2.setPaint(redtowhite); g2.fill(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10)); // fill Arc2D g2.setPaint(red); g2.fill(new Arc2D.Double(x, y, rectWidth, rectHeight, 90, 135, Arc2D.OPEN));

Using the Java 2D APIs to define and render the Graphics and Text public class ShapesDemo2D extends JApplet { final static int maxCharHeight = 15; final static int minFontSize = 6; final static Color bg = Color.white; final static Color fg = Color.black; final static Color red = Color.red; final static Color white = Color.white; final static BasicStroke stroke = new BasicStroke(2.0f); final static BasicStroke wide Stroke = new BasicStroke(8.0f); final static float dash1[] = {10.0f} final static BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);

Dimension totalSize; FontMetrics fontMetrics; public void init() { //Initialize drawing colors setBackground(bg); setForeground(fg); } FontMetrics pickFont(Graphics2D g2, String longString, int xSpace) { boolean fontFits = false; Font font = g2.getFont(); FontMetrics fontMetrics = g2.getFontMetrics(); int size = font.getSize(); String name = font.getName(); int style = font.getStyle();

while ( !fontFits ) if ( (fontMetrics.getHeight() <= maxCharHeight) && (fontMetrics.stringWidth(longString) <= xSpace) ) { fontFits = true; } else { if ( size <= minFontSize ) { fontFits = true; } else { g2.setFont(font = new Font name, style, --size)); fontMetrics = g2.getFontMetrics(); } } } return fontMetrics; }

public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Dimension d = getSize(); int gridWidth = d.width / 6; int gridHeight = d.height / 2; fontMetrics = pickFont(g2, "Filled and Stroked GeneralPath", gridWidth); Color fg3D = Color.lightGray; g2.setPaint(fg3D); g2.draw3DRect(0, 0, d.width - 1, d.height - 1, true); g2.draw3DRect(3, 3, d.width - 7, d.height - 7, false); g2.setPaint(fg); int x = 5; int y = 7; int rectWidth = gridWidth - 2*x; int stringY = gridHeight fontMetrics.getDescent(); int rectHeight = stringY - fontMetrics.getMaxAscent() - y - 2;