Java Reference
In-Depth Information
public
public
void
void
paint
(
Graphics g
) {
g
.
drawImage
(
image
,
20
,
20
,
this
this
);
}
public
public static
void
main
(
String
[]
args
) {
JFrame f
=
new
static
void
new
JFrame
(
"GetImage"
);
f
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
GetImage myApplet
=
new
new
GetImage
();
f
.
setContentPane
(
myApplet
);
myApplet
.
init
();
f
.
setSize
(
100
,
100
);
f
.
setVisible
(
true
true
);
myApplet
.
start
();
}
}
You may sometimes want to display an image more than once in the same panel.
Example 12-5
is a program that paints its background with the same image over and over.
We use the image's
getWidth()
and
getHeight()
methods to find the image's size and the
more regular
getSize()
method on the component itself. As usual, we don't hardcode the
window size in the
paint()
method because the user has the option of resizing with the
mouse.
Example 12-5. TiledImageComponent.java
public
public class
class
TiledImageComponent
TiledImageComponent
extends
extends
JComponent
{
private
private static
static final
final
long
long
serialVersionUID
= -
8771306833824134974L
;
protected
protected
TextField nameTF
,
passTF
,
domainTF
;
protected
protected
Image im
;
public
public static
final
String DEFAULT_IMAGE_NAME
=
"graphics/background.gif"
;
static final
/** Set things up nicely. */
public
public
TiledImageComponent
() {
setLayout
(
new
new
FlowLayout
());
add
(
new
new
Label
(
"Name:"
,
Label
.
CENTER
));
add
(
nameTF
=
new
new
TextField
(
10
));
add
(
new
new
Label
(
"Password:"
,
Label
.
CENTER
));
add
(
passTF
=
new
new
TextField
(
10
));
passTF
.
setEchoChar
(
'*'
);