I'm trying to show an image with a java panel but it's a no go. The code doesn't give any exceptions and/or errors and yet the image doesn't load. The image does exist and I've tried .jpg also but that doesn't work as well.
package feupcraftproject;
import javax.swing.*;
public class frame_jogo extends JFrame
{
public panel_jogo panel;
public frame_jogo()
{
panel = new panel_jogo();
//setLayout(new GridLayout(1,1,0,0));
add(panel);
}
}
package feupcraftproject;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.applet.Applet;
public class panel_jogo extends Applet
{
public BufferedImage back;
public panel_jogo()
{
try
{
back = ImageIO.read(new File("src/Recursos/mapa_piso1.png"));
}
catch (IOException A)
{
JOptionPane.showMessageDialog(null, A.toString());
}
//this.setBackground(Color.BLACK);
}
//@Override
public void paintComponent(Graphics g)
{
//super.paintComponents(g);
g.drawImage(back, 611, 468, this);
}
}
This is a bit inexplicable:
public class panel_jogo extends Applet // ?? Applet ??
Does Applet have a paintComponent(...)
method? I didn't think so.
Edit -- it doesn't and I see that you commented the @Override -- too bad, because it would have told you that no override exists, and so your paintComponent(...)
method is fated to do nothing useful.
Recommendations:
@Override
annotation. It's needed for a reason. paintComponent(...)
method does in fact call the super method, something you've commented out. getPreferredSize()
so that it is in fact large enough to show the entire image at its desired location. It looks like you "borrowed" code that in fact followed my recommendations above but for some unknown reason changed it to force it to misbehave, especially by having it extend Applet. Can you explain your reasoning behind this?
public class panel_jogo extends Applet
{
public BufferedImage back;
public panel_jogo()
{
try
{
back = ImageIO.read(new File("src/Recursos/mapa_piso1.png"));
The Applet
and File
classes do not 'play well together'.
File
. File
objects created can only relate to the client machine, and the mapa_piso1.png
is not (I presume) going to be found on the hard disks of the user's PC! Applet
can load images from the server it came from, by URL
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.