Java Reference
In-Depth Information
java.awt.Graphics
+drawImage(image: Image, x: int, y: int,
bgcolor: Color, observer:
ImageObserver): void
Draws the image in a specified location. The image's top-left corner is at
( x , y ) in the graphics context's coordinate space. Transparent pixels in
the image are drawn in the specified color bgcolor . The observer is the
object on which the image is displayed. The image is cut off if it is
larger than the area it is being drawn on.
Same as the preceding method except that it does not specify a background
color.
Draws a scaled version of the image that can fill all of the available space
in the specified rectangle.
+drawImage(image: Image, x: int, y: int,
observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int,
width: int, height: int, observer:
ImageObserver): void
+drawImage(image: Image, x: int, y: int,
width: int, height: int, bgcolor: Color,
observer: ImageObserver): void
Same as the preceding method except that it provides a solid background
color behind the image being drawn.
F IGURE 13.22
You can apply the drawImage method on a Graphics object to display an image on a GUI component.
L ISTING 13.11 DisplayImage.java
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class DisplayImage extends JFrame {
5
public DisplayImage() {
6
7 }
8
9 public static void main(String[] args) {
10 JFrame frame = new DisplayImage();
11 frame.setTitle( "DisplayImage" );
12 frame.setSize( 300 , 300 );
13 frame.setLocationRelativeTo( null ); // Center the frame
14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15 frame.setVisible( true );
16 }
17 }
18
19
20
add( new ImagePanel());
add panel
class ImagePanel extends JPanel {
panel class
create image icon
get image
private
ImageIcon imageIcon = new ImageIcon( "image/us.gif" );
21
private
Image image = imageIcon.getImage();
22
23 @Override /** Draw image on the panel */
24
25
protected void paintComponent(Graphics g) {
override paintComponent
super .paintComponent(g);
26
27
if (image != null )
28
29 }
30 }
g.drawImage(image, 0 , 0 , getWidth(), getHeight(), this );
draw image
F IGURE 13.23
An image is displayed in a panel.
 
 
Search WWH ::




Custom Search