Chapter 16 Graphics

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Copying an Area

After you create a graphics image, you might want to create copies of the image. Of course, you can redraw the picture, but you can also use the copyArea() method to copy any rectangular area to a new location. The copyArea() method requires six parameters: The x- and y-coordinates of the upper-left corner of the area to be copied The width and height of the area to be copied The horizontal and vertical displacement of the destination of the copy For example, the following line of code causes a Graphics object named gr to copy an area 20 pixels wide by 30 pixels tall from the upper-left corner of your JFrame (coordinates 0, 0) to an area that begins 100 pixels to the right and 50 pixels down: gr.copyArea(0, 0, 20, 30, 100, 50);

Ascent

Ascent is the height of an uppercase character from a baseline to the top of the character.

Descent

Descent measures the part of characters that "hang below" the baseline, such as the tails on the lowercase letters g and j.

clockwise

If you want to travel clockwise from the starting position, you express the degrees as a negative number.

Drawing Arcs

In Java, you can draw an arc using the Graphics drawArc() method. To use the drawArc() method, you provide six arguments: The x- and y-coordinates of the upper-left corner of an imaginary rectangle that represents the bounds of the imaginary circle that contains the arc The width and height of the imaginary rectangle that represents the bounds of the imaginary circle that contains the arc The beginning arc position and the arc angle

Drawing Lines and Shapes

Just as you can draw String using a Graphics object the drawString ( ) method. Java provides you with several methods for drawing a variety of lines geometric shapes. Any line or shape is drawn in the current color you set with the setColor() method. When you do not set a color, lines are drawn in black by default.

Leading

Leading (pronounced ledding) is the amount of space between the bottom of the descent of one line and the top of the characters in the successive line of type.

truth & truth

Painting can be system triggered (for example, when a component is resized) or application triggered (for example, when a user clicks a button). When the paint() method is called, the Graphics object parameter is preconfigured with the appropriate state for drawing on the component, including the color and font. You override the paint() method in your programs when you want specific actions to take place when components must be rendered. You don't usually call the paint() method directly—you call repaint().

counter clockwise arc

The arc angle is the number of degrees over which you want to draw the arc, traveling counterclockwise from the starting position. For example, you can draw a half circle by indicating an arc angle of 180° or a quarter circle by indicating an arc angle of 90°.

Creating Shadowed Rectangles

The draw3DRect() method is a minor variation on the drawRect() method. You use the draw3DRect() method to draw a rectangle that appears to have "shadowing" on two of its edges—the effect is that of a rectangle that is lit from the upper-left corner and slightly raised or slightly lowered. The draw3DRect() method requires a fifth argument in addition to the x- and y-coordinates and width and height required by the drawRect() method. The fifth argument is a Boolean value, which is true if you want the raised rectangle effect (darker on the right and bottom) and false if you want the lowered rectangle effect (lighter on the right and bottom).

truth & truth

The drawString() method requires three arguments: a String, an x-axis coordinate, and a y-axis coordinate. When you use x- and y-coordinates with components, such as JButtons or JLabels, the upper-left corner of the component is placed at the coordinate position, but when you use x- and y-coordinates with drawString(), the lower-left corner of the String appears at the coordinates. The drawString() method is a member of the Graphics class, so you need to use a Graphics object to call it.

fillArc() method

The fillArc() method creates a solid arc. The arc is drawn, and two straight lines are drawn from the arc endpoints to the center of the imaginary circle whose perimeter the arc occupies. For example, assuming you have declared a Graphics object named g, the following two statements together produce the output shown in Figure 16-19: g.fillArc(20, 50, 100, 100, 20, 320); g.fillArc(60, 50, 100, 100, 340, 40); Each of the two arcs is in a circle that has a size of 100 by 100. The first arc almost completes a full circle, starting at position 20 (near two o'clock) and ending 320 degrees around the circle (at position 340, near four o'clock). The second filled arc more closely resembles a pie slice, starting at position 340 and extending 40 degrees to end at position 20.

hight of a font

The height of a font is the sum of the leading, ascent, and descent. Figure 16-29 labels each of these measurements.

fill3DRect() method

There is also a fill3DRect() method for creating filled three-dimensional (3D) rectangles; this method is used in the program in Figure 16-15.

Discovering Font Statistics

Typesetters and desktop publishers measure the height of every font in three parts: ascent, descent, and leading.

Using the paintComponent() Method with JPanels

When you create drawings on a JPanel (or other JComponent) instead of on a JFrame, you should use the paintComponent() method rather than the paint() method. A JFrame's paint() method automatically calls paintComponent() for its components, but JFrame is not a child of JComponent, so it does not have its own paintComponent() method. JGraphicsPanel class that overrides JPanel Its constructor accepts a color to use as a background color. Its only method is a paintComponent() method that overrides the paintComponent() method in the JPanel class. The parameter Graphics object is passed to the parent class constructor, the drawing color is set to yellow, and two small circles are drawn.

Creating Polygons

When you want to create a shape that is more complex than a rectangle, you can use a sequence of calls to the drawLine() method, or you can use the drawPolygon() method to draw complex shapes.

Using Color

You can designate a Graphics color with the setColor() method. As you learned in Chapter 15, the Color class contains 13 constants; you can use any of these constants as an argument to the setColor() method.

Learning More About Fonts

You can discover the fonts that are available on your system by using the getAvailableFontFamilyNames() method, which is part of the GraphicsEnvironment class defined in the java.awt package. The GraphicsEnvironment class describes the collection of Font objects and GraphicsDevice objects available to a Java application on a particular platform. The getAvailableFontFamilyNames() method returns an array of String objects that are the names of available fonts. For example, the following statements declare a GraphicsEnvironment object named ge, and then use the object with the getAvailableFontFamilyNames() method to store the font names in a string array: GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontnames = ge.getAvailableFontFamilyNames(); more of that on page 910-911

truth & truth

You can discover the resolution and screen size on your system by using the getScreenResolution() and getScreenSize() methods, which are part of the Toolkit class. 3. Ascent is the height of an uppercase character from a baseline to the top of the character, and descent measures the part of characters that "hang below" the baseline, such as the tail on the lowercase letter y.

Drawing Ovals

You can draw an oval using the drawRoundRect() or fillRoundRect() method, but it is usually easier to use the drawOval() and fillOval() methods.

Using the setFont ( ) and setColor ( ) Methods

You can improve the appearance of strings drawn using Graphics objects by using the setFont() method.

truth & truth

You can use the drawLine() method to draw a straight line between any two points on the screen. You can use methods named drawRect(), fillRect(), clearRect(), drawOval(), and fillOval() to create a variety of shapes When you draw an arc, the zero-degree position is at three o'clock, and the degree values increase as you move counterclockwise in a 360-degree circle, so the 90-degree position is at 12 o'clock.

Drawing Line

You can use the drawLine() method to draw a straight line between any two points on the screen. The drawLine() method takes four arguments: the x- and y-coordinates of the line's starting point and the x- and y-coordinates of the line's ending point. For example, if you create a Graphics object named pen, then the following statement draws a straight line that slants down and to the right, from position 50, 50 to position 100, 200, as shown in Figure 16-10. pen.drawLine(50, 50, 100, 200); Because you can start at either end when you draw a line, an identical line is created with the following: pen.drawLine(100, 200, 50, 50);

Drawing Rectangle

You could draw a rectangle by drawing four lines. Alternatively, you can use the drawRect() method and fillRect() method, respectively, to draw the outline of a rectangle or to draw a solid, or filled, rectangle. Each of these methods requires four arguments. The first two arguments represent the x- and y-coordinates of the upper-left corner of the rectangle. The last two arguments represent the width and height of the rectangle.

Redisplaying or Rerenedered

a surface aslo is called painting

drawString ( ) method

allows to draw a string in a Frame to other components. it requires three arguments: a String , an axis coordinates,and a y-axis coordinate.

setLocation ( ) Method

allows to place a comment at a specific location within a JFrame content pane.

clearRect( ) method

also requires four arguments and draws a rectangle The difference between using the drawRect() and fillRect() methods and the clearRect() method is that the first two methods use the current drawing color, whereas the clearRect() method draws what appears to be an empty or "clear" rectangle. A rectangle created with the clearRect() method is not really "clear"; in other words, it is not transparent. When you create a rectangle, you do not see objects that might be hidden behind it. Instead, the clearRect() method clears anything drawn from view, showing the original content pane.

simple 3d rec code

import javax.swing.*; import java.awt.*; import java.awt.Color; public class JDemo3DRectangles extends JFrame { public void paint(Graphics gr) { super.paint(gr); final int WIDTH = 60, HEIGHT = 80; gr.setColor(Color.PINK); gr.fill3DRect(20, 40, WIDTH, HEIGHT, true); gr.fill3DRect(100, 40, WIDTH, HEIGHT, false); } public static void main(String[] args) { JDemo3DRectangles frame = new JDemo3DRectangles(); frame.setSize(180, 150); frame.setVisible(true); } }

simple Clear Rec code

import javax.swing.*; import java.awt.*; import java.awt.Color; public class JDemoRectangles extends JFrame { Container con = getContentPane(); public JDemoRectangles() { con.setBackground(Color.BLUE); con.setLayout(new FlowLayout()); } public void paint(Graphics gr) { super.paint(gr); gr.setColor(Color.RED); gr.fillRect(40, 40, 120, 120); gr.setColor(Color.YELLOW); gr.fillRect(80, 80, 160, 160); gr.clearRect(50, 60, 50, 50); } public static void main(String[] args) { JDemoRectangles frame = new JDemoRectangles(); frame.setSize(200, 200); frame.setVisible(true); } } Finally, a smaller, "clear" rectangle is drawn that overlaps the other rectangles. As Figure 16-12 shows, you cannot see the boundaries of the original rectangles in the "clear" area—you simply see that portions of the filled rectangles have been removed from the drawing.

simple panel code

import javax.swing.*; import java.awt.*; import java.awt.Color; public class JGraphicsPanel extends JPanel { public JGraphicsPanel(Color color) { setBackground(color); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.YELLOW); g.fillOval(10, 5, 40, 40); g.fillOval(60, 5, 40, 40); } }

simple setLocation code

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JDemoLocation extends JFrame implements ActionListener { JButton pressButton = new JButton("Press"); int x = 0, y = 0; final int GAP = 30; public JDemoLocation() { setTitle("Location Demo"); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(pressButton); pressButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { pressButton.setLocation(x, y); x += GAP; y += GAP; } public static void main(String[] args) { JDemoLocation frame = new JDemoLocation(); frame.setSize(150, 150); frame.setVisible(true); } } after the user clicks the JButton once, moving it to position 0, 0; after the user clicks it a second time, moving it to position 30, 30; and after the user clicks it a third time, moving it to position 60, 60. If the user continues to click the JButton, it moves off the frame surface. You could add a decision to prevent continued progression of the setLocation() coordinates.

Simple code of repaint

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JDemoPaint extends JFrame implements ActionListener { JButton pressButton = new JButton("Press"); public JDemoPaint() { setTitle("Paint Demo"); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(pressButton); pressButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { System.out.print("Button pressed. "); repaint(); } public void paint(Graphics g) { super.paint(g); System.out.println("In paint method."); } public static void main(String[] args) { JDemoPaint frame = new JDemoPaint(); frame.setSize(150, 100); frame.setVisible(true); } }

simple setFont method code

import javax.swing.*; import java.awt.*; public class JDemoFont extends JFrame { Font bigFont = new Font("Serif", Font.ITALIC, 48); String hello = "Hello"; public void paint(Graphics brush) { super.paint(brush); brush.setFont(bigFont); brush.drawString(hello, 10, 100); } public static void main(String[] args) { JDemoFont frame = new JDemoFont(); frame.setSize(180, 150); frame.setVisible(true); } } Figure 16-6 shows an application that uses the setFont() method with a Graphics object named brush. ***** the word bush is withe the graphic object name When the paint() method executes in the JDemoFont example, bigFont is assigned to the automatically created brush object. Then the brush object is used to draw the hello string at position 10, 100. Figure 16-7 shows the output.

simple poly code

import javax.swing.*; import java.awt.*; public class JStar extends JFrame { public void paint(Graphics gr) { super.paint(gr); int xPoints[] = {42, 52, 72, 52, 60, 40, 15, 28, 9, 32, 42}; int yPoints[] = {38, 62, 68, 80, 105, 85, 102, 75, 58, 60, 38}; gr.drawPolygon(xPoints, yPoints, xPoints.length); } public static void main(String[] args) { JStar frame = new JStar(); frame.setSize(80, 150); frame.setVisible(true); } }

Graphics class

is an abstract class that depends directly from Object and holds data about graphics operations and methods for drawing shapes, text, and images.

Painting

operations fall into two broad categories based on what causes them: System-triggered painting: operations occur when the system asks a component to render its contents. This happens when the component is first made visible, if it is resized, or if it is damaged. For example, a component becomes damaged when another component that previously covered part of it has been moved, revealing a portion that was not visible. Application-triggered painting: operations occur when the internal state of a component has changed. For example, when a user clicks a button, a "pressed" version of the button must be rendered. Whether a paint request is triggered by the system or by an application, a Component's paint() method is invoked. The header for the paint() method is: public void paint(Graphics g) the parameter to the method is a Graphics object.

update ( ) ( part of the repaint)

the repaint ( ) method calls another method named update( ) which clears its Components content pane an calls the paint () method

rounded conners

then use drawRoundRect () method it will require 6 arguments : The first four arguments match the four arguments required to draw a rectangle: the x- and y-coordinates of the upper-left corner, the width, and the height. The two additional arguments represent the arc width and height associated with the rounded corners (an arc is a portion of a circle). If you assign zeros to the arc coordinates, the rectangle is not rounded; instead, the corners are square. At the other extreme, if you assign values to the arc coordinates that are at least the width and height of the rectangle, the rectangle is so rounded that it is a circle.

Creating Graphics Object

when you call paint( ) method form an application , you can use the automatically created Graphics object that is passes to it, but can also instantiate an own Graphics object

repaint ( ) method

you don't call directly the paint paint method ( ) , when can be used when widows needs to updated, such when it contains new images or you have moved a new object onto the screen.


Set pelajaran terkait

Ch 32 Maternity and Newborn Medications

View Set

3. أخلاقيات الأعمال

View Set

Biology: DNA Replication, Cell Cycle and Mitosis

View Set

Radians to Degrees and Degrees to Radians

View Set