The goal of this little program is to load an .jpg image and display it in a Canvas class extended by JPanel, which is displayed in a JFrame object in the Main class, like so:
The Main-class
<code>
package imageloader;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ImageLoader {
public static void main(String[] args)
{
JFrame frame = new JFrame();
Canvas c = new Canvas();
Graphics g = frame.getGraphics();
Loader load = new Loader();
frame.setSize(500, 500);
c.setImage(load.loadImage());
frame.add(c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
</code>
<h1>The Canvas class</h1>
<code>
package imageloader;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class Canvas extends JPanel
{
private BufferedImage img = null;
public Canvas()
{
this.setSize(500, 500);
this.setVisible(true);
}
@Override
public void paint(Graphics g)
{
g.drawLine(0, 0, 250, 250); // just to see if the Canvas is painting, and it does!
g.drawImage(img, 250, 250, null);
repaint();
}
public void setImage(BufferedImage img)
{
this.img = img;
}
}
</code>
<h1>The Loading class</h1>
<code>
package imageloader;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Loader
{
public BufferedImage loadImage()
{
BufferedImage im = null;
try
{
File f = new File("player.jpg");
im = ImageIO.read(f.getAbsoluteFile());
System.out.println("Loaded!"); // this did not apear in my Output-Console in Netbeans
}
catch (IOException e) {}
return im;
}
}
</code>
My main question is already asked in the title. First I compared the code with the Java Documentation Tutorial and changed the Parent class from Canvas.java to Component with little effect. Look here for reference:
Then I found this with Google:
Displaying an image in Swing (on StackOverflow)
Since my JFrame (or component for that matter) did in fact execute the drawLine() function from (0|0) to (250|250) that was not the issue, but I did try out paintcomponent() and paintComponents(), the first drew the line but not the image and seemed considerably slower, the latter did not draw the Line at all, so I switched back to the paint() method again.
Before my little research I tried different things on my own. I changed the Loader class a little up from the Tutorial-Version.
The full tutorial is available here: Link