Solved

animated gif in jLabel

Posted on 2013-11-27
10
588 Views
Last Modified: 2013-11-30
Can I rewrite this class to use an ImageIcon instead of a buffered image?

I would like to be able to use an animated gif inside a jLabel:
private JLabel jLabel = new JLabel(new MyIcon());

Open in new window


private class MyIcon implements Icon {
                        @Override
			public void paintIcon(Component c, Graphics g, int x, int y) {
				Graphics2D g2d = (Graphics2D) g.create();

				try{

					URL dancing = getClass().getResource("/img/dancingCat.gif");
					BufferedImage img2 = ImageIO.read(dancing);

					URL grumpy = getClass().getResource("/img/grumpycat.jpg");
	    			        BufferedImage img1 = ImageIO.read(grumpy);

                                        if(result){
						g2d.drawImage(img2, null, 0,0);
					}else{
						g2d.drawImage(img1, null, 0,0);
					}
		
				}catch(IOException e){
					e.printStackTrace();
				}
				g2d.dispose();
				
		       
			}
}

Open in new window

0
Comment
Question by:Kyle Hamilton
  • 6
  • 4
10 Comments
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39682620
It is hard to give you 100% answer without seeing more of your code, but at a guess, something like the below might work...
private class MyIcon implements Icon {
                         ImageIcon imgIcon1 = null;
                         ImageIcon imgIcon2 = null;

                         public MyIcon() {
				try{

					URL dancing = getClass().getResource("/img/dancingCat.gif");
					imgIcon2 = new ImageIcon(dancing);

					URL grumpy = getClass().getResource("/img/grumpycat.jpg");
	    			        imgIcon1 = new ImageIcon(grumpy);
		
				}catch(IOException e){
					e.printStackTrace();
				}

                        }

                        @Override
			public void paintIcon(Component c, Graphics g, int x, int y) {
                                        if(result){
						imgIcon2.paintIcon(c, g, x, y);
					}else{
						imgIcon1.paintIcon(c, g, x, y);
					}
		       
			}
}

Open in new window

Note that I have also moved the ImageIcon loading code out into a Constructor so that it is only done the once rather than every time paintIcon is called (your original BufferedImage code would be quite inefficient).

If the above doesn't work, then can you either send us the full code so we can see all the interactions, or else can you construct a very simple example program (that compiles and runs) that just shows the current functionality that you have now with switching the BufferedImages and we can try and change that to use ImageIcon.
0
 
LVL 25

Author Comment

by:Kyle Hamilton
ID: 39682624
I've requested that this question be deleted for the following reason:

I fixed a different way.
0
 
LVL 25

Author Comment

by:Kyle Hamilton
ID: 39682625
oops, I didn't see the answer.. didn't mean to delete
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 25

Author Closing Comment

by:Kyle Hamilton
ID: 39682638
thank you. I tried this out, but it doesn't seem to refresh when the condition changes. Although it's still helpful in learning.

I ended up solving the problem by hiding and showing labels which have the ImageIcons hardcoded in. I don't know if that's a good solution, but I have to move on...

Thanks again,
Koza
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39682687
but it doesn't seem to refresh when the condition changes
That is particularly the part that I was thinking about when I was saying above that we would need to see other parts of the code to fully solve your problem. If you are still willing to pursue this, post the full code and we can probably help further.
0
 
LVL 25

Author Comment

by:Kyle Hamilton
ID: 39683613
Here is the original code. It uses the buffered image which does not animate. It has some dependencies, so you will not be able to compile it. If you need the other classes, let me know.

It does work. The "result" determines which image is displayed.

The UI is really secondary in what I'm doing here, so I probably shouldn't spend too much time on it. I have way way a lot of work to do on the actual project. I was procrastinating by mucking around with images :(

thanks for your help.
0
 
LVL 25

Author Comment

by:Kyle Hamilton
ID: 39683615
oops, the code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.imageio.ImageIO;

import java.net.URL;
import java.io.*;

public class KHRETester extends JFrame {

	private static final long serialVersionUID = 1L;
	@SuppressWarnings("unused")
	private Regex reEvaluator = new Regex();

	public KHRETester() {
		super("Regular Expression Tester");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		add(
			new MyJPanel(),
			BorderLayout.CENTER
		);
		setSize(734, 734);
		setLocationRelativeTo(null);
		setResizable(false);
		setVisible(true);
	}
	public static String[] sa;
	 

	public static void main(String[] sa) {
		KHRETester.sa = sa;
		new KHRETester();
	}

	private class MyJPanel extends JPanel implements ActionListener {
		private static final long serialVersionUID = 1L;
		private boolean result = false;
		private JTextField jtfRegex = new JTextField("RegularExpression", 32);
		private JTextField jtfString = new JTextField("TestString", 32);
		private JButton jBtn_Match = new JButton("Match");
		private JButton jBtn_Find = new JButton("Find");
		private JLabel jLabel = new JLabel(new MyIcon());

		public MyJPanel() {
			super();
			jBtn_Match.addActionListener(this);
			jBtn_Find.addActionListener(this);
			add(jtfRegex);
			add(jtfString);
			add(jBtn_Match);
			add(jBtn_Find);
			add(jLabel);
		}
		@Override
		public void actionPerformed(ActionEvent e) {

			if (e.getSource() == jBtn_Match){
				try{
					result = reEvaluator.match(jtfRegex.getText(), jtfString.getText());
				}catch (IOException ioe){
					ioe.printStackTrace();
				}
			}else if (e.getSource() == jBtn_Find){
				try{
					result = reEvaluator.find(jtfRegex.getText(), jtfString.getText(), 0);
				}catch (IOException ioe){
					ioe.printStackTrace();
				}
			}
			System.out.println(
				"Evaluating '" +
				jtfRegex.getText() +
				"' using '" +
				jtfString.getText() +
				"'"
			);

			repaint();
		}
		private class MyIcon implements Icon {
			@Override
			public void paintIcon(Component c, Graphics g, int x, int y) {
				Graphics2D g2d = (Graphics2D) g.create();
				try{

					URL dancing = getClass().getResource("/img/dancingCat.gif");
					BufferedImage img2 = ImageIO.read(dancing);
					URL grumpy = getClass().getResource("/img/grumpycat.jpg");
	    			BufferedImage img1 = ImageIO.read(grumpy);

					if(result){
						g2d.drawImage(img2, null, 0,0);
					}else{
						g2d.drawImage(img1, null, 0,0);
					}
		
				}catch(IOException e){
					e.printStackTrace();
				}
				g2d.dispose();
			}
			@Override
			public int getIconWidth() {
				return 284;
			}
			@Override
			public int getIconHeight() {
				return 426;
			}
		}
	}
}

Open in new window

0
 
LVL 35

Expert Comment

by:mccarl
ID: 39684617
Ahh, I don't like to let things beat me, but I think this one has done it. I have played with your code for a while but didn't really get anywhere. I think that the "animated gif" functionality is tightly bound up between JLabel and ImageIcon that I couldn't find a way to get it to do what you want with a custom Icon class.

I ended up solving the problem by hiding and showing labels which have the ImageIcons hardcoded in
I think this is a fair enough solution, and I can't see too much of an issue with it.

Good luck with your project!
0
 
LVL 25

Author Comment

by:Kyle Hamilton
ID: 39685348
mccarl,

thank you so much trying :) As always, I really appreciate your help.

Cheers,
Koza
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39687498
Not a problem. It's for my own benefit too, to learn more about these things! :)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question