Reputation: 15
Basically here's the deal, I'm trying to load an image from a source file within the Project, but whenever I run the code nothing happens.
Can anyone shed some light on where I am going wrong, and maybe possibly how to get it to draw correctly?
Here's the code:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class EnterTile extends Tile {
public EnterTile() {
setTile();
}
public void setTile() {
try {
BufferedImage img = ImageIO.read(new File("res\\BrokenFenceSwamp.gif"));
Graphics g = img.getGraphics();
g.drawImage(img, 1000, 1000, 8, 8, null);
} catch (IOException e) {
System.out.println("Error " + e);
}
}
public static void main(String args[]) {
EnterTile enterTile = new EnterTile();
}
}
Thanks for taking the time to read this.
Upvotes: 0
Views: 140
Reputation: 139
To load the image correctly you need to:
ImageIO.read(EnterTile.class.getResource("/BrokenFenceSwamp.gif"));
)To draw the image you need to specify where. E.g. canvas if you are using awt library. You can try something like this:
public class Main {
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Image Test");
frame.setSize(400, 800);
frame.setVisible(true);
frame.setFocusable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
Canvas canvas = new Canvas();
canvas.setPreferredSize(new Dimension(400, 800));
canvas.setMaximumSize(new Dimension(400, 800));
canvas.setMinimumSize(new Dimension(400, 800));
frame.add(canvas);
frame.pack();
canvas.createBufferStrategy(2);
BufferStrategy bs = canvas.getBufferStrategy();
Graphics g = bs.getDrawGraphics();
g.clearRect(0, 0, 400, 800);
String path = "/BrokenFenceSwamp.gif";
BufferedImage image = ImageIO.read(Main.class.getResource(path));
g.drawImage(image, 0, 0, null);
bs.show();
g.dispose();
}
}
Upvotes: 1
Reputation: 109613
Getting the Graphics of an image is a facility to be able to draw on images:
BufferedImage img = ImageIO.read(new File("res\\BrokenFenceSwamp.gif"));
Graphics g = img.getGraphics();
g.drawString(img, 100, 100, "Hello World!");
g.dispose();
ImageIO.write(new File("res/TitledBFS.gif"));
It does not draw on the screen.
Graphics
can be memory (here), screen or printer.
To draw on the screen, one would make a full-screen window without title and borders, an on its background draw the image.
That would require becoming acquainted with swing or the newer JavaFX.
Upvotes: 1