根据应用程序或小程序是使用AWT还是Swing,答案会略有不同。
(基本上,以
J诸如
JApplet和
Jframe为开头的类是Swing和
Appletand
frame是AWT。)
无论哪种情况,基本步骤都是:
- 将图像绘制或加载到
Image
对象中。 - 在要绘制背景的绘画事件中绘制背景图像
Component
。
步骤1.
可以通过使用
Toolkit类或通过
ImageIO类来加载图像。
该
Toolkit.createImage方法可用于
Image从中指定的位置加载
String:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");同样,
ImageIO可以使用:
Image img = ImageIO.read(new File("background.jpg");第2步。
Component应该获取背景的绘画方法将被覆盖,并将其绘画
Image到组件上。
对于AWT,要覆盖的
paint方法是方法,并使用传递给该方法
drawImage的
Graphics对象的
paint方法:
public void paint(Graphics g){ // Draw the previously loaded image to Component. g.drawImage(img, 0, 0, null); // Draw sprites, and other things. // ....}对于Swing,要覆盖的
paintComponent方法是的方法
JComponent,并
Image使用在AWT中所做的绘制。
public void paintComponent(Graphics g){ // Draw the previously loaded image to Component. g.drawImage(img, 0, 0, null); // Draw sprites, and other things. // ....}简单组件示例
这是一个
Panel在实例化时加载图像文件并在其自身上绘制图像的:
class BackgroundPanel extends Panel{ // The Image to store the background image in. Image img; public BackgroundPanel() { // Loads the background image and stores in img object. img = Toolkit.getDefaultToolkit().createImage("background.jpg"); } public void paint(Graphics g) { // Draws the img to the BackgroundPanel. g.drawImage(img, 0, 0, null); }}有关绘画的更多信息:
- 在AWT和Swing中绘画
- 课程:从Java教程执行自定义绘画可能会有所帮助。



