base on this thread :Java: Load image from file, edit and add to JPanel i tried to load na image into a JPanel but its not painting it,so here s the deal, as suggested i have created a new class file named JImageComponent which extends from a JComponent, which looks like this :
package in.co.sneh;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
private BufferedImage img;
public class JImageComponent extends JComponent
{
public JImageComponent (BufferedImage bi)
{
img = bi;
}
@Override
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 0, this);
}
}
then in the applet form class ,when i click on the loadPicture Button, the action performed looks like this :
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int retVal = chooser.showDialog(AppletForm.this, "Attach");
if (retVal == JFileChooser.APPROVE_OPTION) {
picFile = chooser.getSelectedFile();
try {
image = ImageIO.read(picFile);
JImageComponent jcomp = new JImageComponent(image);
Graphics2D g = image.createGraphics();
jcomp.paintComponents(g);
// Draw here on the graphics
//g.dispose();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
jPanel6.add(jcomp);
System.out.println("Testing" + picFile);
} catch (IOException e) {
e.printStackTrace();
}
to me everything is in place however the image is not showing when in the file explorer choose the image, can anyone help me out? Thanks in advance, Romulo Romero
After adding a new component to the container, you need to call
jPanel6.revalidate();
jPanel6.repaint();
Also applets cannot load resources from the local file system unless they are signed.
Note:
While having a a single JImageComponent
would be better, JLabel
components already offer the functionality of switching images by using setIcon.