-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageTest.java
66 lines (53 loc) · 1.66 KB
/
ImageTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package image;
import javax.swing.*;
import java.awt.*;
/**
* @author Cay Horstmann
* @version 1.34 2015-05-12
*/
public class ImageTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new ImageFrame();
frame.setTitle("ImageTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/**
* A frame with an image component
*/
class ImageFrame extends JFrame {
public ImageFrame() {
add(new ImageComponent());
pack();
}
}
/**
* A component that displays a tiled image
*/
class ImageComponent extends JComponent {
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
private Image image;
public ImageComponent() {
// image = new ImageIcon("blue-ball.gif").getImage();
image = new ImageIcon(ClassLoader.getSystemResource("blue-ball.gif")).getImage();
}
public void paintComponent(Graphics g) {
if (image == null) return;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
// draw the image in the upper-left corner
g.drawImage(image, 0, 0, null);
// tile the image across the component
for (int i = 0; i * imageWidth <= getWidth(); i++)
for (int j = 0; j * imageHeight <= getHeight(); j++)
if (i + j > 0)
g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j * imageHeight);
}
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}