Solved

animated gif in jLabel

Posted on 2013-11-27
10
586 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 77
JUnit 4 @Before and @BeforeClass differences 3 59
How to convert String matching to regex in java 4 32
printf performancy 11 33
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

786 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