Java Reference
In-Depth Information
Table 14.6
Useful Methods of BufferedImage Objects
public BufferedImage(int width, int height, int type)
Constructs an image buffer of the given size and type. Valid types are
BufferedImage.TYPE_INT_ARGB: An image with a transparent background.
BufferedImage.TYPE_INT_RGB: An image with a solid black background.
public Graphics getGraphics()
Returns the pen for drawing on this image buffer.
Another way to create an icon besides loading a file containing the icon is to draw
an icon yourself. You can create a blank image buffer by using a BufferedImage
object and draw on it by using a Graphics pen, as we did with the DrawingPanel in
Supplement 3G. (In fact, the DrawingPanel is implemented with an internal
BufferedImage .) BufferedImage is a class in the java.awt.image package, so if
you want to use it, you must import the package:
import java.awt.image.*; // for BufferedImage
The constructor and some useful methods of the BufferedImage class are shown
in Table 14.6.
To use a BufferedImage , construct one of a particular size and type (we recom-
mend BufferedImage.TYPE_INT_ARGB ), then get the Graphics object from it using
the getGraphics method. You can then issue standard drawing commands such as
drawRect or fillOval . Once you're finished drawing on the BufferedImage , create
a new ImageIcon object and pass the BufferedImage to the ImageIcon constructor.
You can set this ImageIcon as the icon for an onscreen component by calling
setIcon on that component and passing the ImageIcon as the parameter, as
demonstrated in the following code:
JButton button = new JButton();
button.setText("My drawing");
// create a shape image icon for this button
BufferedImage image = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.YELLOW);
g.fillRect(10, 20, 80, 70);
g.setColor(Color.RED);
g.fillOval(40, 50, 25, 25);
ImageIcon icon = new ImageIcon(image);
button.setIcon(icon);
You can also use a BufferedImage as the icon image for a frame by calling its
setIconImage method:
frame.setIconImage(image);
 
 
Search WWH ::




Custom Search