In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the knowledge points of JAVA graphic design volume". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Note 1: the user interface artifacts provided in AWT (such as buttons, lists, menus, dialogs, etc.) do not contain similar pure graphics objects (such as Line or Circle classes)
Since the original AWT does not allow pure graphics objects at design time, Rectangle, Polygon and Point do not have any ability to draw graphics. let me put it another way,
Rectangle, Polygon, and Point do not have draw methods. All you can do is set up and get information about the geometric entities they represent.
To replace pure, graphable objects, AWT uses a simple-- albeit inflexible and difficult-to-extend-- mode:
Each AWT component comes entirely from its own java.awt.Graphics object, although some of its graphical operations can be implemented in its associated artifacts.
Graphics can also be drawn to a variety of output devices, such as out-of-picture buffers and printers-see Chapter 24, "double buffering Technology" and Section 18.4, "Printing".
Please look at the two tables first (both ignore the java.awt.peer method):
Table 3-1 passes a jdk method for a reference to Graphics
━━
Software package class square method
──
Java.awt Canvas paint (Graphics g)
Component paint (Graphics g)
Component paintAll (Graphics g)
Component print (Graphics g)
Component printAll (Graphics g)
Component update (Graphics g)
Container paint (Graphics g)
Container paintComponents (Graphics g)
Container print (Graphics g)
Container printComponents (Graphics g)
ScrollPane printComponents (Graphics g)
Java.beans Property_Enditor paintValue (Graphics gre rectangle r)
Property_EnditorSupport paintValue (Graphics gre rectangle r)
━━
Table 3-2 returns the JDK method of the Graphics reference
━━
Software package class square method
──
Java.awt Component getGraphics ()-(for the most commonly used)
Image getGraphics ()
PaintJob getGraphics ()
Graphics create ()
Graphics create (int xreint ymenint wreint h)
━━
1.java.awt.Graphics function: define a real tool for accepting graphics operations (display images and text, draw and fill switches, clip image operations, etc.)
In almost all applet programs (and applications), AWT processing Graphics is used to serve images.
A fragment of an applet program:
Public void paint (Graphics g) {
G.drawString ("Hello Graphics Java World", 75100)
...}
In addition, when performing image operations within the widget, the following graphic properties are maintained in each Graphics:
The color used to draw and fill shapes.
A font used to describe text.
Cut and paste rectangle.
Draw mode (XOR or Paint).
The translation origin for displaying and clipping coordinates.
2.Graphics parameter
The two main responsibilities of the Graphics class:
(1) set and obtain drawing parameters
(2) perform graphics operations in the output device (primary)
Four parameters used in the Graphics class
Table 3-3
| | method |
-|
(a) Color void setColoer (Color color)
Color getColor ()
-|
(B) font void setFont (Font f)
And Font getFont ()
-
Font metric (property is read-only) the font metric returned by FontMetrics getFontMetrics () is combined with the current font of Graphics
The font scale returned by FontMetrics getFontMetrics (Font f) is combined with the specified font
-|
(C) cut-and-paste rectangle void setClip (int xreint yminint wpenint h)
Rectangle getClipBounds ()
The void setClip (Shape) Shape interface is part of java 2D api. The shape represented by Shape can be non-rectangular.
So it can define a non-rectangular clip rectangle for the output device.
Shape getClip ()
Void clipRect (int xreint yjinint wreint h) calculates a new clipping rectangle that is the same as the original clipping rectangle and
The intersection of the clipping rectangles specified by the parameters in the
-|
(d) graphic mode (attribute is write-only) void setPaintMode () (default mode) sets paint graphics mode, which means that subsequent shading operations will overwrite existing graphics
Void set setXORMode () allows you to draw and erase existing graphics without interfering with the graphics below them
-|-
A simple example of applet should be noted:
Example 1.
Import java.applet.Applet
Import java.awt.*
Public class RectTest extends Applet {
Public void paint (Graphics g) {
G.drawRect (2, 2, 4, 4) / / * Line A
}
}
File:// any HTML file such as 001.html
Enter: appletviewer 001.html under the file:// command line
The coordinate path drawn is as follows: a rectangle with 5 pixel units squared.
(2) → (6) → (6) → (2) → (2) the color of the brush is specified by calling Graphics.setColor (Color).
Note:
When you draw a rectangle by calling Graphics.drawRect (), the result is an extra row of pixels on the right and below the rectangle. This is because it is passed to
The parameters in Graphics.drawRect () define the path the brush follows, not the size of the rectangle itself. Because the brush is drawn along the coordinate path mentioned above
Rectangular, so g.drawRect actually draws a rectangle with a width and height of 5 pixel units-- instead of 4 pixel units as you might imagine.
Tip 1: "graphic coordinates are between pixels", not above them. The graphical method of specifying coordinates specifies the movement of the brush path, usually per pixel square.
The path of the brush paint pixel is the starting point → right → under → left → start point. As a result, the graphic method of drawing the shape of the graph will have an additional row of pixels on the right and below the rectangle.
The use of tip 1: when drawing the boundaries around a component
Public void paint (Graphics g) {
Dimension size=getSize ()
G.drawRect; / / without minus one, the right edge and bottom edge boundaries will be drawn on the outside of the component without seeing the part.
}
Replace the / / * line in example 1 with A--->g.drawRect (2Jing 2jin4); replace it with g.fillRect (2Jing 2Jet 4).
Note: the parameter passed to fillRect () at this time specifies the same coordinate path as when you called drawRect () earlier. However, the Graphics of the filled form factor
Method fills the interior of the path, so the filled rectangle is 4 pixels wide and 4 pixels high
3.Graphics reference
There are two ways to use a reference to the Graphics of a component. These two methods are: override the methods in previous tables 3-1 (passing a reference to Graphics), or call tables 3-2
The methods listed (will return a reference to Graphics). It is worth noting that Graphics references are returned from the getGraphics () method in Component, Image, and PrintJob
Instead of being a reference to a Graphics reference, a copy of the original Graphics is returned. In the following chapters, you will find this is a very important concept.
Another simple applet example: emphasize again that the Graphics reference refers to a copy of the real Graphics related to the artifact
Import java.applet.Applet
Import java.awt.*
Public class CopyTest extends Applet {
Public void paint (Graphics g) {
SetForeground (Color.yellow); / / sets the foreground color to yellow
G.drawLine (0re0reg getSize (). Width-1, getSize (). Height-1)
}
}
The result may not be what you might expect: at the beginning of the line drawing, the color of the line may not be yellow (black flash, use IE to see.)
Reason: call Component.setForeground () to change the current color of the Graphics in the component-in this case
The color is changed to yellow. SetFroeground () affects the Graphics of applet, but does not affect the pass to paint ()
A copy of the Graphics of the Therefore, the color of the line does not change to yellow when paint () is called for the first time. When calling
When drawLine (), the Graphics passed to paint () is out of sync with the actual Graphics. When paint () is called later
Passed to paint () is a new copy of applet's Graphics, so the result of the call to setForeground () can
Change the current color of applet's Graphics to yellow.
If you change the applet program:
Import java.applet.Applet
Import java.awt.*
Public class CopyTest2 extends Applet {
Public void paint (Graphics g) {
SetForeground (Color.yellow); / / the next line would do just as well as the following
/ / g.setColor (Color.yellow)
Graphics copy = getGraphics ()
Try {
System.out.println ("g =" + g.getColor () + "copy=" + copy.getColor ())
Copy.drawLine (0re0reg getSize (). Width-1, getSize (). Height-1)
}
Finally {
Copy.dispose ()
}
}
} file://, then the lines drawn at the beginning are yellow and printed under DOS:
G=java.awt.Color [rang 0meng 0m m 0m m 0m 0] copy=java.awt.Color [r e e 255 ref. Gr e 255m b 0]
G=java.awt.Color [ringing 255, gregory 255, reel 0] copy=java.awt.Color [rang 255, recordgime 255, reel 0]
G=java.awt.Color [ringing 255, gregory 255, reel 0] copy=java.awt.Color [rang 255, recordgime 255, reel 0]
Explanation: the Graphics passed to paint () will be ignored and a new Graphics will be obtained by calling the getGraphics () method
Apply this new Graphics to draw straight lines. Because Graphics is obtained after calling setForeground (), Graphics
The current color, that is, the color of the lines, will turn yellow.
Lifetime of 4.Graphics referenc
Note: in addition to referencing the real copy, Graphics references passed to methods such as paint () and update () are valid only during method execution.
Once the method returns, the reference will no longer be valid (forced reloading, such as refreshing, etc., can redraw the applet)
Example:
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class HoldRef extends Applet {
Private Graphics oldg
Private boolean first = true
Public void paint (Graphics g) {
If (first) {
Oldg = g
First = false
}
Oldg.drawLine (0re0reg getSize (). Width-1, getSize (). Height-1)
}
}
As you can see, the Graphics references passed to the method have a short lifetime because they are limited resources that must be processed, and each Graphics represents the image environment
Is provided by the local window system. The image environment is usually set to be available within a limited number, and when the call returns, pass the Graphics reference to the
The caller will dispose of it carefully. For example, when the call to Component.Paint () returns, the caller processes the Graphics passed to paint ().
5. Although Java comes with garbage collection, there are still two places in AWT for developers to deal with limited system resources, and processing Graphics is one of them.
(note: windows and dialogs must also be processed, see Chapter 16, "Windows, frames, and dialogs.") There are two things to pay attention to when dealing with Graphics
That is, when and how to deal with it
Processing Graphics rules: if you call one of the getGraphics methods listed in Table 3-2 to get a reference to Graphics
Or create a Graphics through Graphics.create (), then you have the responsibility to deal with them
To process Graphics by calling Graphics.dispose (), look at a program snippet:
Public void someMethodInAComponent () {/ / code fragment
Graphics g=getGraphics ()
If (glossary null) {
Try {
File://do something with g-if an exception is thrown
File://the finally block will be executed
}
Finally {
G.dispose () / / crucial is critical because ignoring it will cause the window system to run out of graphics environment, which can cause problems in most operations
}
}
}
What file:// should note here is that it is not groundless not to do null detection on g. If getGraphics () is called before the appositive of the component is created, it does return null.
The call to Graphics.dispose () is placed in the finally block, while control of the Graphics is performed in the corresponding try block. This guarantees a call to dispose ()
Will be placed within the event, and exceptions will be thrown from the try block.
Tip 2: "passing a copy of the method reference of a drawing reference"
The use of tip 2:
Graphics represents the local graphics environment and is a typical limited resource. Therefore, the returned Graphics reference must be handled by calling the Graphics.dispose () method.
A method of passing a Graphics reference, like Component.paint (), is a method that does not require manual setting processing-when the call returns, the caller of the method must handle the
Are you tired? Me too. Work hard! Come on!
6. Draw and fill shapes (line (Lines) broken line (Polylines) rectangle (Rectangles) arc (Arcs) ellipse (Ovals) polygon (Polygons) text (Text) image (Images))
6.1how to draw a straight line: Graphics.drawLine (int x ther int y m int x 2 int y 2)
AWT cannot draw a straight line with a fixed width, but a straight line drawn with a graphic pen is usually one pixel wide.
Lines are often drawn as solid lines-there is no specified pattern of lines, such as dots or dashed lines. However, in Java 2D API, there is extensive support for different line types and pen sizes.
Random straight line example: starting point, length, direction and color are all random
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class PickupSticks extends Applet {
Private static Color [] colors = {
Color.white, Color.black, Color.blue, Color.red
Color.yellow, Color.orange, Color.cyan, Color.pink
Color.magenta, Color.green}
Public void init () {
Button button = new Button ("scatter")
Add (button)
Button.addActionListener (new ActionListener () {
Public void actionPerformed (ActionEvent event) {
Repaint ()
}
});
}
Public void paint (Graphics g) {
For (int iTun0; I < 500; + + I) {
Int x = (int) (Math.random () * 100)
Int y = (int) (Math.random () * 100)
Int deltax = (int) (Math.random () * 100)
Int deltay = (int) (Math.random () * 100)
G.setColor (colors [(int) (Math.random () * 10)])
G.drawLine (x _ journal _ y _ journal x + deltax, y + deltay)
}
}
}
6.2.Using broken lines: drawPolyline (int [] xPoints,int [] yPoints,int numPoints)
One array specifies the x coordinate value of each point, the other array specifies the y coordinate value of the point, and the number of points of the broken line to be drawn
The number of points is equal to the number of segments + 1. If the starting point and the end point do not coincide, the broken line drawn is not closed.
Examples of broken lines:
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class Polylines extends Applet {
Private static Color [] colors = {
Color.white, Color.black, Color.blue, Color.red
Color.yellow, Color.orange, Color.cyan, Color.pink
Color.magenta, Color.green}
Public void init () {
Button button = new Button ("repaint")
Add (button)
Button.addActionListener (new ActionListener () {
Public void actionPerformed (ActionEvent event) {
Polylines.this.repaint ()
}
});
}
Public void paint (Graphics g) {
File://int arraySize = ((int) (Math.random () * 100)); / / original example
Int arraySize = 4 / there are too many lines, so I set it to 4
Int [] xPoints = new int [arraySize]
Int [] yPoints = new int [arraySize]; / / xPoints and yPoints should be equal
File://int[] yPoints = new int [arraySize-1]; / / unequal, compile-time error-free, runtime gives you a surprise:).
For (int iTuno; I < xPoints.length; + + I) {
XPoints [I] = ((int) (Math.random () * 200))
YPoints [I] = ((int) (Math.random () * 200))
}
G.setColor (colors [(int) (Math.random () * 10)])
G.drawPolyline (xPoints, yPoints, arraySize)
ShowStatus (arraySize + "points")
}
}
6.3 draw a rectangle:
There are three kinds of rectangles:
(1) physical (solid)
(2) fillet (rounded)
(3) 3D
The drawing method is as follows:
Void clearRect (int xreint ymenint wreint h)
Void drawRect (int xreint ymenint wreint h)
Void drawRoundRect (int xjinint yjingint wminint hminint arcWidth,int arcHeight)
The added parameter arcWidth is used to set the horizontal diameter of the arc and arcHeight is used to set the diameter in the vertical direction
Void draw3DRect (int xreint yjingint wreint hrecom Boolean raise)
The added parameter raise is used to specify whether the 3D effect is convex or concave. The 3D effect is convex in ture and concave in false.
Void fillRoundRect (int xjinint yjingint wminint hminint arcWidth,int arcHeight)
Void fillRect (int xreint ymenint wreint h)
Void fill3DRect (int xreint yjingint wreint hrecom Boolean raise)
Example 2 of drawing a rectangle:
The file://applet program is equipped with three buttons and a check box, and the code for drawing the rectangle is encapsulated in the paint method of applet
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class RandomRectangles extends Applet {
Private static Color [] colors = {
Color.white, Color.black, Color.blue, Color.red
Color.yellow, Color.orange, Color.cyan, Color.pink
Color.magenta, Color.green}
Private int numRects = 10
Private boolean fill = false,// check box is used to specify whether the rectangle is filled
Raise = false
Round = false
ThreeD = false;// variable cannot start with a number like 3D
Public void init () {/ / each button represents the type of rectangle being drawn
Button rectsButton = new Button ("rectangle")
Button roundbutton = new Button ("rounded rectangle")
Button threeDButton = new Button ("3D rectangle")
Checkbox fillCheckbox = new Checkbox ("fill")
Add (rectsButton)
Add (roundButton)
Add (threeDButton)
Add (fillCheckbox)
RectsButton.addActionListener (new ActionListener () {
Public void actionPerformed (ActionEvent event) {
Round = false
ThreeD = false
Repaint ()
}
});
RoundButton.addActionListener (new ActionListener () {
Public void actionPerformed (ActionEvent event) {
Round = true
ThreeD = false
Repaint ()
}
});
ThreeDButton.addActionListener (new ActionListener () {
Public void actionPerformed (ActionEvent event) {
ThreeD = true
Round = false
Repaint ()
}
});
FillCheckbox.addItemListener (new ItemListener () {
Public void itemStateChanged (ItemEvent event) {
Fill = ((Checkbox) (event.getsource () .getState ()
}
});
}
When file:// draws all rectangles, it uses a 1-pixel wide pen, because this size is only allowed in AWT.
Public void paint (Graphics g) {
For (int iTuno; I < numRects; iTunes +) {
Point lhc = randomPoint (); / / left hand corner
Dimension size = randomDimension ()
G.setColor (colors [(int) (Math.random () * 10)])
If (round) {
If (fill)
G.fillRoundRect (lhc.x,lhc.y,size.width,size.height
(int) (Math.random () * 250)
(int) (Math.random () * 250)
Else
G.drawRoundRect (lhc.x,lhc.y,size.width,size.height
(int) (Math.random () * 250)
(int) (Math.random () * 250)
}
Else if (threeD) {
Before file:// draws a 3D rectangle, the color of Graphics is set to bright gray before its 3D effect can be seen.
G.setColor (Color.lightGray)
If (fill)
G.fill3DRect (
Lhc.x,lhc.y,size.width,size.height,raise)
Else
G.draw3DRect (
Lhc.x,lhc.y,size.width,size.height,raise)
}
Else {
If (fill)
G.fillRect (lhc.x,lhc.y,size.width,size.height)
Else
G.drawRect (lhc.x,lhc.y,size.width,size.height)
}
Raise = raise? False: true
}
}
Private Dimension randomDimension () {
Return new Dimension ((int) (Math.random () * 250)
(int) (Math.random () * 250)
}
Private Point randomPoint () {
Return new Point ((int) (Math.random () * 250)
(int) (Math.random () * 250)
}
}
6.4 Arc drawing: the arc is the only figure that is not closed but can be filled
Drawing method: void drawArc (int x.int yreint yreint wjinint hminint startAngle,int endAngle)
Void fillArc (int xjinint yjingint wminint hminint startAngle,int endAngle)
The meaning of the parameter: the coordinate path is specified by the x ~ (th) y (width) y (height) arc. The last two are the start and end angles of the arc.
Simple example:
Import java.applet.Applet
Import java.awt.*
Public class DrawArc extends Applet {
Public void paint (Graphics g) {
G.setColor (Color.blue)
G.drawArc / / width and height are 151and 101pixels respectively. Do you know why?
G.setColor (Color.yellow)
G.fillArc (50, 50, 100, 100, 200, 90270); / / 100 wide, 200 pixels high, because it is filled.
}
}
6.5 draw an ellipse (not rounded rectangle)
Drawing method: / / the width and height are the same, and the drawing is a circle
Void drawOval (int xreint ymenint wreint h)
Void fillOval (int xreint ymenint wreint h)
Parameter meaning: a rectangular box with an outer frame tangent to the ellipse
If you are smart, you must know the ellipse drawn by drawOval (). The suitable rectangle is 1 pixel wide and 1 pixel high.
6.6 draw polygons
Drawing method: / / similar to broken lines, another: the initial point and the end point are not the same point polygons will be closed automatically
Void drawPloygon (int [] xPoints,int [] yPoints,int [] numPoints)
Void drawPolygon (Polygon polygon)
Void fillPloygon (int xPoints,int [] yPoints,int [] numPoints)
Void fillPolygon (Polygon polygon)
Note: although non-graphical Polygon and Rectangle classes are provided in AWT, the Graphics class does not provide
The drawRect (Rectangle) method, although there is a drawPolygon (Polygon) method.
6.7 draw text
Drawing method:
Void drawString (String sdirection int xreint y)
Void drawChars (char [], int offset,int length,int xjinint y)
Void drawBytes (byte [], int offset,int length,int xjinint y)
Note: the xpeny position of the drawn text corresponds to the text baseline, not the upper-left corner of the text, and is different from the rectangle.
See windows's SDK programming. The SDK programming of JDK and windows is very similar, while learning can be footnotes to each other and improve each other.
A simple sentence: a character begins with its bottom line, such as A with about the left foot.
Tip 3:
If the string and the rectangle are drawn in the same place, the string will be displayed above the rectangle
The offset and length parameters are used to specify the offset of the start position in the array and the number of characters drawn, respectively. (the Graphics class does not provide the ability to rotate text)
6.8 convert the origin of the coordinate system: if not specified, the origin is generally set at the upper left corner in the Graphics coordinate system
Coordinate conversion method: Graphics.translate ()
Two integer parameter values: the point depicted in the original coordinate system will become the new origin in the transformed coordinate system
Reason for changing coordinates: one reason is that there is no scroll bar in the container and its contents have to be scrolled, as in the following example (click the mouse to scroll the graph)
An example of changing the coordinate system:
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class TranslateTest extends Applet {
Image image
Point pressed = new Point (), lastTranslate = new Point ()
Public void init () {
Image = getImage (getCodeBase (), "Rabbit.gif"); / / just find a .gif file in the IE cache
Try {
MediaTracker mt = new MediaTracker (this)
Mt.addImage (image, 0)
Mt.waitForID (0)
}
Catch (InterruptedException e) {
E.printStackTrace ()
}
AddMouseListener (new MouseAdapter () {
Public void mousePressed (MouseEvent e) {
Java.awt.Point loc = e.getPoint ()
File://Point loc = e.getPoint (); / / is the original, but says at compile time
File://--TranslateTest.java:19: incompatible t
File://--found: java.awt.Point
File://--required: Point
File://--Point loc = e.getPoint ()
File://-- ^
File://----- added java.awt. In front of. What's the reason? THINK IN JAVA says that Point has several classes (in awt, in 2D). So.
/ / adjust mouse pressed location for
/ / translation...
Pressed.x = loc.x-lastTranslate.x
Pressed.y = loc.y-lastTranslate.y
}
});
AddMouseMotionListener (new MouseMotionAdapter () {
Public void mouseDragged (MouseEvent e) {
Java.awt.Point loc = e.getPoint (); / / added java.awt
Point translate = new Point (loc.x-pressed.x
Loc.y-pressed.y)
Graphics g = getGraphics ()
Try {
G.clearRect (0dint 0
GetSize (). Width,getSize (). Height)
G.translate (translate.x, translate.y)
ShowStatus ("Translating Graphics:" +
Translate)
G.drawImage (image, 0,0, TranslateTest.this)
}
Finally {
G.dispose ()
}
LastTranslate = translate
}
});
}
Public void paint (Graphics g) {
G.drawImage (image, 0,0, this)
}
}
Clipping: each Graphics has an associated clipping rectangle. Clip rectangles are so named because they copy the rectangles they represent. In addition,
With the development of Java 2D API, the switch in the clipping area can be set to any switch, not just a rectangle.
Drawing method: same as Table 3-3
Void setClip (int xreint yjinint wreint) file:// sets the area to be cut and pasted is a rectangular area
Void setClip (Shape) file:// sets the area to be clipped and pasted in any shape
Rectangle getClipBounds () file:// returns that the clipping area is a rectangular area
Shape getClip () file:// returns that the clipping area is of any shape
Void clipRect (int xreint yreint wreint h) file:// sets the clipping rectangle to the intersection of the current clipping rectangle and the rectangle that becomes unspecified in the method.
See example 2 for examples in this section.
Tip 4: "pass the clipped Graphics to Component.paint ()"
For beginners of AWT, it is common to pass Graphics to the paint method where the clipping rectangle is smaller than the component. As a result, the underlying overlay paint method does not work.
Disturb the clipping rectangle of the Graphics it accepts. When paint () draws the contents of the component, the shading operation is still performed. In some examples (such as double buffering and animation design)
By updating only the clipped area instead of drawing the complete content and relying on clipping to repair the damaged area, you can get better results
6.10 graphic mode: see Table 3-3
The most common use of XOR mode is to use rubber band generation on existing graphics (a common use in drawing programs and when selecting multiple objects)
All examples of the face are set to paint mode, so in this section we will focus on XOR mode
The XOR schema is described in the document as follows: Graphics.setXORMode (Color)
When drawing operations are performed,pixels which are the current color are changed to the
Specify color,and vice versa . Pixels that are of colors other than those two color are changed
In an unpredictable but reversible manner;if the figure is drawn twice,then all pixels are
Restored to their original values .
The second sentence states that if you copy the image twice in XOR mode, the graphics below it will not be affected.
An example of using XOR mode rubber band generation: pull on an image to generate a rectangle
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class xortest extends Applet {
Java.awt.Point pressed, last
Image image
Boolean firstRect
Public void init () {
Image = getImage (getCodeBase (), "Rabbit.gif")
Try {
MediaTracker mt = new MediaTracker (this)
Mt.addImage (image, 0)
Mt.waitForID (0)
}
Catch (InterruptedException e) {
E.printStackTrace ()
}
AddMouseListener (new MouseAdapter () {
Public void mousePressed (MouseEvent e) {
FirstRect = true
Pressed = e.getPoint ()
}
Public void mouseReleased (MouseEvent e) {
If (pressed! = null) {
Java.awt.Point released = e.getPoint ()
Rectangle clip = new Rectangle ()
Graphics g = getGraphics ()
Dimension size = getSize ()
Try {
Clip.x = pressed.x
Clip.y = pressed.y
Clip.width = Math.abs (released.x-pressed.x)
Clip.height = Math.abs (released.y-pressed.y)
G.clearRect (0pr 0pr size.widthje size.height)
G.setClip (clip)
G.drawImage (image, 0,0, xortest.this)
}
Finally {
G.dispose ()
}
}
}
Public void mouseClicked (MouseEvent e) {
Repaint ()
}
});
AddMouseMotionListener (new MouseMotionAdapter () {
Public void mouseDragged (MouseEvent e) {
Java.awt.Point loc = e.getPoint ()
Graphics g = getGraphics ()
Try {
G.setXORMode (getBackground ())
If (firstRect) {
FirstRect = false
}
Else {
G.drawRect (pressed.x, pressed.y,Math.abs (pressed.x-last.x), Math.abs (pressed.y-last.y))
}
G.drawRect (pressed.x, pressed.y,Math.abs (loc.x-pressed.x), Math.abs (loc.y-pressed.y))
Last = e.getPoint ()
}
Finally {
G.dispose ()
}
}
});
}
Public void paint (Graphics g) {
G.drawImage (image, 0,0, this)
}
}
6.11 create a graphic
When implementing a method that passes a Graphics reference, it is best to ensure that the result of the method does not cause a change in Graphics. In other words, when the method returns
The Graphics should be the same as before the call. There are exceptions to this rule, of course, and we can safely say that when paint () returns
On return, the caller of paint (Graphics) only deals with Graphics. Therefore, you can change the Graphics passed to paint () while ignoring maintenance
Its initial state. However, in other cases, it is not so clear whether Graphics must retain its initial state. Under the circumstances
It is best to accept the security steps and ensure that the Graphics is not changed. There are two ways to do this.
One way is that all the initial features of the Graphics can be stored locally and then reset before the method returns:
File://code fragment
Public void notSurelfGraphicsShouldChangeState (Graphics g) {
Color oldColor=g.getColor ()
Font oldFont=g.getFont ()
File://modify g's color and font and perfoRM graphical operations
G.setColor (oldColor); / / restore old color
G.setfont (oldFont) / / restore old font
Obviously, it doesn't matter if one or two attributes are changed. It's troublesome to have a large number of attributes modified and restored.
Method 2: it is more convenient to create a copy of the Graphics and use it instead of the Graphics passed to the method
Public void notSurelfGraphicsShouldChangeState (Graphics g) {
Graphics copy=g.create ()
Try {
File://use copy for rendering
}
Finally {
G.dispose (); / / crucial
}
}
For the example in the lifespan section of the 4.Graphics reference, the applet program retains a Graphics reference because it is passed
The Graphics to paint () is processed by the caller, so the Graphics reference is valid only during the call to paint ()
Now let's create a copy of Graphics that will not be processed after calling paint (), as follows
Import java.applet.Applet
Import java.awt.*
Import java.awt.event.*
Public class HoldRef2 extends Applet {
Private Graphics copy
Private boolean first = true
Public void paint (Graphics g) {
If (first) {
/ / note: copy is never disposed off
File:// fatal error, that is, a copy of Graphics was not processed
File:// in practice, the license makes a copy reference of a class member and, in another method, handles it in time in the appropriate motor
Copy = g.create ()
Copy.setColor (Color.red)
Copy.setFont (new Font ("Times Roman", Font.BOLD, 14))
First = false
}
Copy.drawString ("Red Text", 10,10)
}
}
How to create a Graphics:
Graphics create () / / creates an exact copy of Graphics
Graphics create is also a copy, but the origin of the returned Graphics is converted to
Coordinate, the clipping rectangle is converted to the intersection of the original clipping rectangle and the specified rectangle
Example:
Import java.applet.Applet
Import java.awt.*
Public class CreateTest extends Applet {
Private Image image
Public void init () {
MediaTracker mt = new MediaTracker (this)
Image = getImage (getCodeBase (), "Rabbit.gif")
Try {
Mt.addImage (image, 0)
Mt.waitForID (0)
}
Catch (Exception e) {
E.printStackTrace ()
}
}
Public void paint (Graphics g) {
Graphics copy = g.create (image.getWidth (this), 0100100)
Try {
System.out.println ("g:" + g.getClip () .toString ())
System.out.println ("copy:" + copy.getClip () .toString ())
G.drawImage (image, 0,0, this)
Copy.drawImage (image, 0,0, this)
}
Finally {
Copy.dispose ()
}
}
}
Load the image and create a copy of the Graphics to be passed through the paint method of applet
The origin of the copy is transformed to (imw,0), and imw refers to the width of the graph.
The copy also has its clipping rectangle, which is set to the original Graphics and specified by (image.getWidth (this), 0100100).
The intersection of the rectangles of Because the clipping rectangle of the initial Graphics covers the area occupied by the applet program, the intersection of the two rectangles is determined by the
(image.getWidth (this), 0100100).
Tip: the copied Graphics has been converted because the drawImage () is called to draw the image in (0jin0)
Aah! It's almost over! A brief summary:
(1) the coordinate system of the graphics operation is set at the upper left corner of the device, the growth directions of the x and y axes are down and right respectively, and the coordinates are between the pixels.
In the Graphics method, the shape is drawn by setting the coordinates of the graph rather than pixels. The graphic pen moves to the right and below the coordinate path
So the shape of the shape results in an extra one on the right and one at the bottom of the figure.
The pixel row of the. On the other hand, the shape fills the interior of the shape, and the size of the fill is the same as the coordinate path
(2) AWT does not provide classes that support special shapes, such as Line and Circle classes. Java.awt.Graphics provides a large number of methods to draw and
Fill in graphics, draw text, set graphic parameters. But there are limitations, so you should learn more about Java 2D API.
(3) each Graphics contacts a graphics environment in a native potential window system. Therefore, what Graphics describes must be handled by hand.
Limited resources. If you return a Graphics reference to get a Graphics by calling a method, Graphics.dispose ()
Must be called to release system resources for Graphics. On the other hand, methods that pass Graphics references usually do not have to deal with Graphics.
Generally, the caller of these methods is responsible for handling the Graphics
This is the end of the content of "what are the knowledge points of JAVA graphic design volume". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.