문제 설명
기존 이미지가 화면에 그려지지 않는 이유는 무엇입니까? (Why won't my existing image draw to the screen?)
기본적으로 여기에 거래가 있습니다. 프로젝트 내의 소스 파일에서 이미지를 로드하려고 하지만 코드를 실행할 때마다 아무 일도 일어나지 않습니다.
누가 내가 잘못 가고 있는 부분과 올바르게 그리는 방법을 알려줄 수 있습니까?
코드는 다음과 같습니다.
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();
}
}
감사합니다. 시간을 내어 읽어 주셔서 감사합니다.
참조 솔루션
방법 1:
To load the image correctly you need to:
- Have the res folder (where the image is stored) marked as a resource folder.
- When you call the read() method of ImageIO, you need to pass a URL. To do that you need to use {className}.class.getResource({path}) (In your case
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();
}
}
방법 2:
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.
(by PureShpongled、Bogomil Dimitrov、Joop Eggen)