I was working on my GUI project and i wanted to add an animated GIF but the code wasn't running then i decided to google the answer (Obvious response) but i failed then i looked into some stack overflow codes and found the second code from here but it also failed as well. Please someone help me escape this misery.
I Used this code first and it gave me this error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Class_GUI.<init>(Class_GUI.java:54)
at Class_Driver.main(Class_Driver.java:3)
Process finished with exit code 1
The Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Class_GUI implements MouseListener {
private JFrame jFrame = new JFrame ();
private JPanel jPanel = new JPanel ();
private JLabel minusLabel = new JLabel ("-");
private JLabel closeLabel = new JLabel ("X");
private JLabel imageLabel = new JLabel ();
public Class_GUI () {
ImageIcon icon = new ImageIcon("E:\\Mehroz\\The Dollars\\The_Dollars\\Icons & Images\\Dollars_Logo.png");
jFrame.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
jFrame.setSize (700, 900);
jFrame.setUndecorated (true);
jFrame.setShape (new RoundRectangle2D.Double (0, 0, 700, 900, 25, 25));
jFrame.setIconImage(icon.getImage());
jFrame.setLocationRelativeTo (null);
jFrame.setLayout (null);
FrameDragListener frameDragListener = new FrameDragListener (jFrame);
jFrame.addMouseListener (frameDragListener);
jFrame.addMouseMotionListener (frameDragListener);
jPanel.setBounds (0, 0, 700, 900);
jPanel.setBackground (new Color (0, 0, 0, 150));
jPanel.setLayout (null);
minusLabel.setBounds (645, 5, 25, 30);
minusLabel.setForeground (new Color (0, 0, 0));
minusLabel.setFont (new Font ("Arial", Font.BOLD, 50));
minusLabel.setToolTipText ("Minimize");
minusLabel.setBorder (BorderFactory.createBevelBorder (0));
minusLabel.setCursor (Cursor.getPredefinedCursor (Cursor.HAND_CURSOR));
minusLabel.addMouseListener (this);
closeLabel.setBounds (670, 5, 25, 30);
closeLabel.setForeground (new Color (255, 0, 0));
closeLabel.setFont (new Font ("Arial", Font.BOLD, 25));
closeLabel.setToolTipText ("Close");
closeLabel.setBorder (BorderFactory.createBevelBorder (0));
closeLabel.setCursor (Cursor.getPredefinedCursor (Cursor.HAND_CURSOR));
closeLabel.addMouseListener (this);
Error Line
BufferedImage img = new BufferedImage (Transparency.OPAQUE,
Image.SCALE_SMOOTH, Image.SCALE_SMOOTH);
try {
img = ImageIO.read(jFrame.getClass().getResource("DollarsLogo.gif"));
} catch (IOException e) {
e.printStackTrace ();
}
ImageIcon icons = new ImageIcon(img);
JLabel label = new JLabel(icons);
jPanel.add(label);
jPanel.add (minusLabel);
jPanel.add (closeLabel);
jFrame.add (jPanel);
jFrame.setVisible (true);
}
@Override
public void mouseClicked (MouseEvent e) {
if (e.getSource () == minusLabel) {
jFrame.setState (JFrame.ICONIFIED);
} else if (e.getSource () == closeLabel) {
System.exit(0);
}
}
@Override
public void mousePressed (MouseEvent e) { }
@Override
public void mouseReleased (MouseEvent e) { }
@Override
public void mouseEntered (MouseEvent e) {
if (e.getSource () == minusLabel) {
minusLabel.setBackground (new Color (110, 225, 110, 150));
} else if (e.getSource () == closeLabel) {
closeLabel.setBackground (new Color (110, 225, 110, 150));
}
jFrame.repaint ();
}
@Override
public void mouseExited (MouseEvent e) {
if (e.getSource () == minusLabel) {
minusLabel.setBackground (new Color (255, 255, 255, 225));
} else if (e.getSource () == closeLabel) {
closeLabel.setBackground (new Color (255, 255, 255, 225));
}
jFrame.repaint ();
}
}
/**<\>------------------------------------------------------------------------------------------------------------</>**/
Then I Tried this code from some of the previous answers and it game me a null pointer exception error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at PlayAnimatedGif$AnimatedGif.<init>(PlayAnimatedGif.java:135)
at PlayAnimatedGif$TestPane.<init>(PlayAnimatedGif.java:62)
at PlayAnimatedGif$1.run(PlayAnimatedGif.java:47) <14 internal calls>
Process finished with exit code 0
The Code:
import java.awt.image.BufferedImage;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class PlayAnimatedGif {
public static void main (String[] args) {
new PlayAnimatedGif ();
}
public PlayAnimatedGif () {
EventQueue.invokeLater (new Runnable () {
@Override
public void run () {
try {
UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame ("Testing");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setLayout (new BorderLayout ());
frame.add (new TestPane ());
frame.pack ();
frame.setLocationRelativeTo (null);
frame.setVisible (true);
}
});
}
public class TestPane extends JPanel {
private AnimatedGif ag;
public TestPane () {
URL url = getClass ().getResource ("DollarsLogo.gif");
try {
ag = new AnimatedGif (this, url);
} catch (IOException ex) {
ex.printStackTrace ();
}
ag.play ();
}
@Override
public Dimension getPreferredSize () {
return new Dimension (200, 200);
}
@Override
protected void paintComponent (Graphics g) {
super.paintComponent (g);
Graphics2D g2d = (Graphics2D) g.create ();
BufferedImage currentFrame = ag.getCurrentFrame ();
if (currentFrame != null) {
int x = (getWidth () - currentFrame.getWidth ()) / 2;
int y = (getHeight () - currentFrame.getHeight ()) / 2;
g2d.drawImage (currentFrame, x, y, this);
}
g2d.dispose ();
}
}
public static class AnimatedGif {
public enum DisposalMethod {
RESTORE_TO_BACKGROUND,
RESTORE_TO_PREVIOUS,
DO_NOT_DISPOSE,
UNSPECIFIED;
public static DisposalMethod find (String text) {
DisposalMethod dm = UNSPECIFIED;
switch (text) {
case "restoreToBackgroundColor":
dm = RESTORE_TO_BACKGROUND;
break;
}
return dm;
}
}
private List<ImageFrame> frames;
private int frame;
private Timer playTimer;
private JComponent player;
protected AnimatedGif (JComponent value) {
this.player = value;
frames = new ArrayList<> (25);
playTimer = new Timer (0, new ActionListener () {
@Override
public void actionPerformed (ActionEvent e) {
frame++;
if (frame >= frames.size ()) {
frame = 0;
}
player.repaint ();
playTimer.setDelay (frames.get (0).getGraphicControlExtension ().getDelayTime ());
}
});
}
public AnimatedGif (JComponent player, URL url) throws IOException {
this (player);
The Error Line
try (InputStream is = url.openStream (); ImageInputStream stream =
ImageIO.createImageInputStream (is))
{
Iterator readers = ImageIO.getImageReaders (stream);
if (!readers.hasNext ()) {
throw new RuntimeException ("no image reader found");
}
ImageReader reader = (ImageReader) readers.next ();
reader.setInput (stream); // don't omit this line!
int n = reader.getNumImages (true); // don't use false!
System.out.println ("numImages = " + n);
for (int i = 0; i < n; i++) {
BufferedImage image = reader.read (i);
ImageFrame imageFrame = new ImageFrame (image);
IIOMetadata imd = reader.getImageMetadata (i);
Node tree = imd.getAsTree ("javax_imageio_gif_image_1.0");
NodeList children = tree.getChildNodes ();
for (int j = 0; j < children.getLength (); j++) {
Node nodeItem = children.item (j);
NamedNodeMap attr = nodeItem.getAttributes ();
switch (nodeItem.getNodeName ()) {
case "ImageDescriptor":
ImageDescriptor id = new ImageDescriptor (
getIntValue (attr.getNamedItem ("imageLeftPosition")),
getIntValue (attr.getNamedItem ("imageTopPosition")),
getIntValue (attr.getNamedItem ("imageWidth")),
getIntValue (attr.getNamedItem ("imageHeight")),
getBooleanValue (attr.getNamedItem ("interlaceFlag")));
imageFrame.setImageDescriptor (id);
break;
case "GraphicControlExtension":
GraphicControlExtension gc = new GraphicControlExtension (
DisposalMethod.find (getNodeValue (attr.getNamedItem ("disposalMethod"))),
getBooleanValue (attr.getNamedItem ("userInputFlag")),
getBooleanValue (attr.getNamedItem ("transparentColorFlag")),
getIntValue (attr.getNamedItem ("delayTime")) * 10,
getIntValue (attr.getNamedItem ("transparentColorIndex")));
imageFrame.setGraphicControlExtension (gc);
break;
}
}
frames.add (imageFrame);
}
} finally {
}
}
public BufferedImage getCurrentFrame () {
// If this was a optimised GIF, we would need to be
// merging frames together to produce the current frame
// This would then need to be reset each time we cycle...
return frames.isEmpty () ? null : frames.get (frame).getImage ();
}
public void play () {
if (!frames.isEmpty ()) {
frame = 0;
playTimer.setDelay (frames.get (0).getGraphicControlExtension ().getDelayTime ());
playTimer.start ();
player.repaint ();
}
}
public void stop () {
playTimer.stop ();
}
protected String getNodeValue (Node node) {
return node == null ? null : node.getNodeValue ();
}
protected int getIntValue (Node node) {
return node == null ? 0 : getIntValue (node.getNodeValue ());
}
protected boolean getBooleanValue (Node node) {
return node == null ? false : getBooleanValue (node.getNodeValue ());
}
protected int getIntValue (String value) {
return value == null ? 0 : Integer.parseInt (value);
}
protected boolean getBooleanValue (String value) {
return value == null ? false : Boolean.parseBoolean (value);
}
public class ImageFrame {
private BufferedImage image;
private ImageDescriptor imageDescriptor;
private GraphicControlExtension graphicControlExtension;
public ImageFrame (BufferedImage image) {
this.image = image;
}
protected void setImageDescriptor (ImageDescriptor imageDescriptor) {
this.imageDescriptor = imageDescriptor;
}
protected void setGraphicControlExtension (GraphicControlExtension graphicControlExtension) {
this.graphicControlExtension = graphicControlExtension;
}
public GraphicControlExtension getGraphicControlExtension () {
return graphicControlExtension;
}
public BufferedImage getImage () {
return image;
}
public ImageDescriptor getImageDescriptor () {
return imageDescriptor;
}
}
public class GraphicControlExtension {
private DisposalMethod disposalMethod;
private boolean userInputFlag;
private boolean transparentColorFlag;
private int delayTime;
private int transparentColorIndex;
public GraphicControlExtension (DisposalMethod disposalMethod, boolean userInputFlag, boolean transparentColorFlag, int delayTime, int transparentColorIndex) {
this.disposalMethod = disposalMethod;
this.userInputFlag = userInputFlag;
this.transparentColorFlag = transparentColorFlag;
this.delayTime = delayTime;
this.transparentColorIndex = transparentColorIndex;
}
public int getDelayTime () {
return delayTime;
}
public DisposalMethod getDisposalMethod () {
return disposalMethod;
}
public int getTransparentColorIndex () {
return transparentColorIndex;
}
public boolean isTransparentColorFlag () {
return transparentColorFlag;
}
public boolean isUserInputFlag () {
return userInputFlag;
}
}
public class ImageDescriptor {
private int imageLeftPosition;
private int imageTopPosition;
private int imageHeight;
private int imageWeight;
private boolean interlaced;
public ImageDescriptor (int imageLeftPosition, int imageTopPosition, int imageHeight, int imageWeight, boolean interlaced) {
this.imageLeftPosition = imageLeftPosition;
this.imageTopPosition = imageTopPosition;
this.imageHeight = imageHeight;
this.imageWeight = imageWeight;
this.interlaced = interlaced;
}
public int getImageHeight () {
return imageHeight;
}
public int getImageLeftPosition () {
return imageLeftPosition;
}
public int getImageTopPosition () {
return imageTopPosition;
}
public int getImageWeight () {
return imageWeight;
}
public boolean isInterlaced () {
return interlaced;
}
}
}
}
Sorry for this monstrosity.
I Hope the COVID kills all the bugs in my codes.
p.s. Don't ask why the Gif name is The Dollars. ;)