I tried loading images, I found a code and it works well, the code for loading an Image is in the constructor, I tried to move it to a button action, and also to a filechooser. But never load an image. there are no errors in the code, and I tested the clauses using print statements, they show that the clauses are passed.
this is an SSCCE:
The constructor code is separated into two parts Upper and Lower. To demonstrate the problem alternate between these codes by commenting and uncommentting each.
the Lower part will work; it loads the image from the constructor.
the upper part set the JPanels and the JButtons required to load the image from Action code.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ImgLoadTest extends JPanel implements ActionListener
{
File file;
BufferedImage img;
JButton fileChooserButton;
JButton showImgButton;
JPanel imgePanel;
JPanel widgetPanel;
JFileChooser fileChooser;
@Override
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 60, null);
}
public ImgLoadTest()
{
//Upper:
// fileChooser = new JFileChooser();
//
// fileChooserButton = new JButton("Browse");
// fileChooserButton.addActionListener(this);
// showImgButton = new JButton("Show Image");
// showImgButton.addActionListener(this);
//
// imgePanel = new JPanel();
// widgetPanel = new JPanel();
// this.setLayout(new BorderLayout());
// widgetPanel.add(fileChooserButton);
// widgetPanel.add(showImgButton);
// this.add(imgePanel, BorderLayout.CENTER);
// this.add(widgetPanel, BorderLayout.EAST);
/*
* try alternating (comment/uncomment) between
* the upper code (in this constructor)
* and the lower code below;
*/
//Lower:
try
{
img = ImageIO.read(new File("D:\\De.JPG"));
} catch (IOException e)
{
}
}
@Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == fileChooserButton)
{
int reternedValue = fileChooser.showOpenDialog(ImgLoadTest.this);
if (reternedValue == JFileChooser.APPROVE_OPTION)
{
file = fileChooser.getSelectedFile();
try
{
img = ImageIO.read(file);
System.out.println("File chooser: Image accepted");
this.repaint();
} catch (IOException err)
{
System.out.println("error " + err);
}
} else
{
System.out.println("No Image");
}
}
if (source == showImgButton)
{
try
{
System.out.println("button: Image accepted");
img = ImageIO.read(new File("D:\\De.JPG"));
repaint();
} catch (IOException err)
{
System.out.println("No Image");
System.out.println("error " + err);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Image load test");
frame.setSize(new Dimension(400, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImgLoadTest imgLoadTest = new ImgLoadTest();
frame.add(imgLoadTest);
frame.setVisible(true);
}
}
Just assigning the
BufferedImageimgwill not make the image appear. You could add aJLabelwhich contains the image: