2016-01-23 77 views
0

我想用文本和图像GIF显示JLabel。当我从Test类调用showLabel()方法时,我只能看到文本。我不知道如何刷新这个图像来显示它。我读的是在这种情况下AWT的问题...刷新JFrame上的图像

问:如何在我的JLabel中显示此GIF图像?

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); 
    } 
} 
+2

貌似程序无法找到图片; “PHOTO.gif”位于何处?如果它在项目的'src'文件夹中,则使用'getClass()。getResource(“PHOTO.gif”)'。如果它不在您的项目中,您必须输入图像的完整路径作为参数。 (例如'c:\\ temp \\ PHOTO.gif') –

+1

“TranslucentPane”类没有必要。您尚未更改任何JPanel的默认行为。 JPanel默认是不透明的。摆脱那个阶级。 – camickr

回答

1

我同意LuxxMiner。
最有可能的是,图像无法找到。
要检查您可以使用下面的检查路径:

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; 
    } 
} 

所以不是:

frame.add(new JLabel(label, icon, JLabel.CENTER)); 

尝试以下操作:

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));