My java code a image on a label which in this code is b2. What I want to do is when the user hits the button for the image that is on the label to be exported. Right now there is a error stating
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class javax.swing.ImageIcon cannot be cast to class java.awt.image.BufferedImage (javax.swing.ImageIcon and java.awt.image.BufferedImage are in module java.desktop of loader 'bootstrap') at time.simple$1.actionPerformed(simple.java:51).
Line 51 is unscaledButtonImage = (BufferedImage) icon;. So there is a runtime error every time I try to run this code.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
class simple {
Frame f;
JLabel b2=new JLabel("");;
simple() throws IOException{
f=new JFrame();
b2.setIcon(new ImageIcon("/Users/johnzalubski/Desktop/dropIn/Complete-Audi-Buying-Guide-gear-patrol-lead-full.jpg"));
JButton b3 = new JButton("Exported");
File file = new File("aa.png");
f.add(b2,BorderLayout.CENTER);
f.add(b3,BorderLayout.SOUTH);
f.setSize(400,500);
f.setVisible(true);
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BufferedImage unscaledButtonImage;
Icon icon = b2.getIcon();
unscaledButtonImage = (BufferedImage) icon;
BufferedImage scaledButtonImage =
new BufferedImage(400, 1000, unscaledButtonImage.getType());
Graphics g = scaledButtonImage.createGraphics();
g.drawImage(unscaledButtonImage, 0, 0, 400, 1000, null);
g.dispose();
b2.setIcon(new ImageIcon(scaledButtonImage));
try {
ImageIO.write(scaledButtonImage, "png",file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
public ImageIcon ResizeImage(String ImagePath)
{
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(b2.getWidth(), b2.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
public static void main(String[] args) throws IOException {
new simple();
}
}