Reputation: 402
I am trying to create a game using JFrame, and it requires that I draw images. I am using graphics2D to paint them, but I couldn't figure out why this gave me no output:
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Image img = Toolkit.getDefaultToolkit().getImage("src/resources/main/my_image");
g2d.drawImage(img, 0, 0, null);
g2d.finalize();
}
And I haven't been able to find a way to draw an image that actually works.
Upvotes: 0
Views: 2823
Reputation: 1642
1. Your first error might be as stated in the Java Tutorial. You shouldn't override paint()
:
The
paintComponent
method is where all of your custom painting takes place.
2. As per this answer you should also not call finalize()
on your graphics object, but as far as I can tell, it should not interfere with your drawing. See this answer also for additional details on why finalize()
is not needed here.
3. Did you check that your component is even seen on screen? If it is of size 0x0, the image may be drawn, but still not be seen. One easy way I find to check whether a component is seen, is to (temporarily) change its border to a green line to verify its size and location.
4. See Joop Eggen's answer for resource loading, which could also lead to you not seeing the image.
Upvotes: 0
Reputation: 109547
First about "resources/main" (and the missing file extension). If this would happen to be a maven project the path should be:
src/main/resources/my_image.png
For reading a resource file one can do something like:
Image img = ImageIO.read(getClass().getResourceAsStream("/my_image.png"));
This file then resides with the classes on the class path, one can check the path, in a jar by unzipping it. One gets a NullPointerException if the path is incorrect.
Upvotes: 1