What I am trying to do is create a gui that allows you to select an image, display the image, and then perfom actions on it for a school project. This is what happens on startup. Perfect! However, when I update the icon, it puts the new icon behind it:
Here is the code I'm using on my Jlabel:
ImageIcon imageIcon = new ImageIcon();
try {
imageIcon = new ImageIcon(ImageIO.read(new File("/Users/ryanauger/Repos/JavaGUI/GUI/Images/cameraIcon.png")));
} catch (IOException e2) {
// TODO Auto-generated catch block
imageIcon = new ImageIcon();
e2.printStackTrace();
}
JLabel lblNewLabel = new MyJLabel(imageIcon);
lblNewLabel.setBounds(0, 6, 600, 600);
frame.getContentPane().add(lblNewLabel);
JButton btnNewButton = new JButton("Pick Image File");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser jfc;
jfc = new JFileChooser();
File f = new File(System.getProperty("user.dir"));
jfc.setCurrentDirectory(f);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
jfc.showOpenDialog(btnNewButton);
File selFile = jfc.getSelectedFile();
try {
lblNewLabel.setIcon(new ImageIcon(ImageIO.read(new File(selFile.getAbsolutePath()))));
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(selFile.getAbsolutePath());
e1.printStackTrace();
}
}
});
I am brand new to java, so any help is appreciated. Thanks!
EDIT: Here is the code for MyJLabel:
class MyJLabel extends JLabel
{
ImageIcon imageIcon;
public MyJLabel(ImageIcon icon)
{
super();
this.imageIcon = icon;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(imageIcon.getImage(),0,0,getWidth(),getHeight(),this);
}
}