Reputation: 319
I want to show JLabel with text and image GIF. When i call showLabel() method from Test class i see only text. I don't know how to refresh this image to show it. I read is problem with AWT in this case...
Question: How to show this GIF image in my JLabel?
LabelTest.class
public class LabelTest{
private JWindow frame;
private JLabel jLabel;
ImageIcon icon = new ImageIcon("PHOTO.gif");
public LabelTest() {
}
public void showLabel(String label) {
frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.setBackground(new Color(255, 255, 255));
frame.setContentPane(new TranslucentPane());
frame.add(new JLabel(label, icon, JLabel.CENTER));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.paintAll(frame.getGraphics());
}
public void hideLabel() {
frame.dispose();
}
}
Test.class
public class Test {
public static void main(String[] args){
try {
LabelTest p = new LabelTest();
p.showLabel("I'M LABEL...");
Thread.sleep(5000);
p.hideLabel();
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
TranslucentPane.class
public class TranslucentPane extends JPanel {
public TranslucentPane() {
setOpaque(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
Upvotes: 1
Views: 356
Reputation: 2147
I agree with LuxxMiner.
Most probably, the image can't be found.
To check the path you can use the following check:
public ImageIcon loadImageIconFromPath(String path) {
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
So instead of:
frame.add(new JLabel(label, icon, JLabel.CENTER));
Try the following:
ImageIcon icon = loadImageIconFromPath("PHOTO.gif");
if (icon != null)
frame.add(new JLabel(label, icon, JLabel.CENTER));
else
frame.add(new JLabel("Missing image", JLabel.CENTER));
Upvotes: 2