g.drawImage
时间: 2023-10-24 07:15:51 浏览: 72
Java开发贪吃蛇小游戏(源代码+课程设计论文)
5星 · 资源好评率100%
g.drawImage() is a method in Java that is used to draw an image onto a graphics context. It takes the following parameters:
1. Image – the image to be drawn.
2. X-coordinate of the image – the x-coordinate of the image on the graphics context.
3. Y-coordinate of the image – the y-coordinate of the image on the graphics context.
4. Image observer – an object that will be notified when the image is drawn.
Here is an example of how to use g.drawImage() to draw an image:
```
import java.awt.*;
import javax.swing.*;
public class DrawImage extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Load the image
ImageIcon img = new ImageIcon("image.jpg");
// Draw the image at (10,10)
g.drawImage(img.getImage(), 10, 10, this);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawImage());
frame.setSize(300, 300);
frame.setVisible(true);
}
}
```
In this example, we create a JPanel and override its paintComponent() method to draw an image on it. We load the image using an ImageIcon and then use g.drawImage() to draw the image at (10,10) on the JPanel. Finally, we create a JFrame and add the JPanel to it to display the image.
阅读全文