Solved

animated gif in jLabel

Posted on 2013-11-27
10
577 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
allStar challenge 1 41
countAbc challenge 9 49
What is the latest versions eclipse neon 2 120
Strange loading of website behaviour 3 23
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

705 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now