For two days I was trying to load an image into JPanel
from a file. I couldn't!
I used JLabel
and Icon
and it's loaded okay, but I need to load the image to a JPanel
directly, is that impossible?
Because almost I saw many and many related problems like this and many people recommended the person who asks the question to load the image into a label!
this is the code :
public class ReadingImage extends JPanel {
JPanel panel;
JFrame frame;
JPanel secPanel;
private BufferedImage img;
public ReadingImage(String path){
frame = new JFrame();
frame.setVisible(true);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
secPanel = new JPanel();
secPanel.setVisible(true);
//secPanel.setLayout(new FlowLayout());
secPanel.repaint();
frame.getContentPane().add(secPanel);
try{
FileImageInputStream fi = new FileImageInputStream(new File(path));
//System.out.println(path);
img = ImageIO.read(fi);
this.repaint();
}
catch (IOException io ){ io.printStackTrace();}
}
@Override
protected void paintComponent(Graphics g){
super.paintComponents(g);
if (img!=null){
g.drawImage(img, 0, 0, this);
repaint();
}
}
}
It's not throwing any exception, but it's not displaying the image in the JPanel
!
I adjusted the code many and many times..
any help in this :)
thanks,