So I have a project on image segmentation to complete, and the first stage is to get Java to display an image.
The problem I'm having is that I can get a window to appear, however the image I have loaded does not get rendered.
If I am doing this completely wrong then please then me know. I've spent the afternoon looking for clear explanations on handling images with Java however I haven't found any good, clear resources.
I have two classes at the moment: the main class, and the image loading class.
This is my main class:
import javax.swing.*;
public class LoadImageMain extends JFrame {
public static void main(String[] args) {
displayImage("HelloWorld.png");
}
public static void displayImage(String path) {
JFrame frame = new JFrame("Display Image");
LoadImage panel = new LoadImage(path);
frame.setSize(1200, 800);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.setVisible(true);
}
}
My second class which is meant to render the image:
public class LoadImage extends JPanel {
private Image img;
public LoadImage(String path) {
img = getImage(path);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
public Image getImage(String path) {
Image tempImg = null;
try {
tempImg = Toolkit.getDefaultToolkit().getImage(path);
}
catch (Exception e) {
System.out.println("Image not found. Error: " + e.getMessage());
}
return tempImg;
}
}