2014-03-05 40 views
3

我有一個JFrame。在那裏我有兩個容器,即兩個JPanel。一個小組擁有圖像。其他人擁有JButton。然後將這兩個添加到JTabbedPane。.gif圖像不會將其添加到JTabbed窗格

我的問題是使用.gif圖像時,圖像與任何其他正常的.jpg圖像一樣變得靜止。任何人都可以幫助我一些更多的想法?

這裏是我的代碼:

import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.Frame; 
import java.awt.Graphics; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.URL; 
import java.net.UnknownHostException; 
import javax.imageio.ImageIO; 
import javax.imageio.stream.ImageInputStream; 
import javax.swing.Icon; 
import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JDesktopPane; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTabbedPane; 
import javax.swing.SwingUtilities; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.UIManager.LookAndFeelInfo; 

public class ICLOUD implements ActionListener { 

private BufferedImage bg; 
JButton b1; 
private Object frame1; 
JFrame frame2 = new JFrame(); 

    JDesktopPane desktop = new JDesktopPane(); 
    public ICLOUD() { 
    try { 
     URL url = this.getClass().getResource("anigif.gif"); 
     bg = ImageIO.read(url); 

    } catch (IOException ex) { 

    } 

    JPanel tabPanel = new JPanel(new GridBagLayout()) { 
     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.drawImage(bg, 0, 0, getWidth(), getHeight(), this); 
     } 


     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(400, 300); 
     } 
    }; 



    JPanel buttons = new JPanel(new GridLayout(4, 1, 15, 15)); 
    buttons.setOpaque(false); 



    ImageIcon icon5 = new ImageIcon(ICLOUD.class.getResource("hi.jpg")); 

    b1=new JButton("Hello"); 

    buttons.add(b1); 





    tabPanel.add(buttons); 


    JTabbedPane tabPane = new JTabbedPane(); 
    tabPane.addTab(null,icon5, tabPanel); 

    JFrame frame = new JFrame("I-CLOUD"); 
    b1.setVisible(true); 
    frame.setContentPane(tabPane); 
    frame.pack(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationByPlatform(true); 
    frame.setVisible(true); 
} 






public static void main(String[] args) { 

    try { 
     for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (Exception e) { 

    } 
      ICLOUD r=new ICLOUD(); 
     } 






@Override 
public void actionPerformed(ActionEvent e) { 
    // TODO Auto-generated method stub 

} 



} 
+0

這是'ImageIO'和'JPanel'繪製方式的限制。如果這對您很重要,請考慮使用'JLabel'並通過'ImageIcon'加載圖像。可以使用你的方法完成,是的,但你將負責加載框架和設置動畫線程... – MadProgrammer

+0

@ MadProgrammer-你能提出任何其他方法嗎? – user3320152

+0

除了使用'ImageIcon'?使用'ImageIO'子圖像功能從'GIF'中讀取每張圖像並自己動畫... – MadProgrammer

回答

8

讓我證明你自己挖孔成

你可以這樣做......

BufferedImage img = ImageIO.read(this.getClass().getResource("anigif.gif")); 
ImageIcon icon = new ImageIcon(img); 
JLabel label = new JLabel(icon); 
add(label); 

或者你可以做...

AnimatedGif

現在,這是令人遺憾的不足之處,僅用於舉例目的。它不支持的處置方法或優化的照片與圖像...所以你可以開始想象的,將被要求使這項工作...很多額外的工作量......

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 
import javax.imageio.ImageIO; 
import javax.imageio.ImageReader; 
import javax.imageio.metadata.IIOMetadata; 
import javax.imageio.stream.ImageInputStream; 
import javax.swing.JComponent; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import org.w3c.dom.NamedNodeMap; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

public class PlayAnimatedGif { 

    public static void main(String[] args) { 
     new PlayAnimatedGif(); 
    } 

    public PlayAnimatedGif() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private AnimatedGif ag; 

     public TestPane() { 
      URL url = getClass().getResource("/playanimatedgif/ajax-loader.gif"); 
      try { 
       ag = new AnimatedGif(this, url); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
      ag.play(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      BufferedImage currentFrame = ag.getCurrentFrame(); 
      if (currentFrame != null) { 
       int x = (getWidth() - currentFrame.getWidth())/2; 
       int y = (getHeight() - currentFrame.getHeight())/2; 
       g2d.drawImage(currentFrame, x, y, this); 
      } 
      g2d.dispose(); 
     } 
    } 

    public static class AnimatedGif { 

     public enum DisposalMethod { 
      RESTORE_TO_BACKGROUND, 
      RESTORE_TO_PREVIOUS, 
      DO_NOT_DISPOSE, 
      UNSPECIFIED; 

      public static DisposalMethod find(String text) { 

       DisposalMethod dm = UNSPECIFIED; 

       switch (text) { 
        case "restoreToBackgroundColor": 
         dm = RESTORE_TO_BACKGROUND; 
         break; 
       } 

       return dm; 

      } 
     } 

     private List<ImageFrame> frames; 
     private int frame; 
     private Timer playTimer; 

     private JComponent player; 

     protected AnimatedGif(JComponent value) { 
      this.player = value; 
      frames = new ArrayList<>(25); 
      playTimer = new Timer(0, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        frame++; 
        if (frame >= frames.size()) { 
         frame = 0; 
        } 
        player.repaint(); 
        playTimer.setDelay(frames.get(0).getGraphicControlExtension().getDelayTime()); 
       } 
      }); 
     } 

     public AnimatedGif(JComponent player, URL url) throws IOException { 
      this(player); 
      try (InputStream is = url.openStream(); ImageInputStream stream = ImageIO.createImageInputStream(is)) { 
       Iterator readers = ImageIO.getImageReaders(stream); 
       if (!readers.hasNext()) { 
        throw new RuntimeException("no image reader found"); 
       } 
       ImageReader reader = (ImageReader) readers.next(); 
       reader.setInput(stream);   // don't omit this line! 
       int n = reader.getNumImages(true); // don't use false! 
       System.out.println("numImages = " + n); 
       for (int i = 0; i < n; i++) { 
        BufferedImage image = reader.read(i); 
        ImageFrame imageFrame = new ImageFrame(image); 

        IIOMetadata imd = reader.getImageMetadata(i); 
        Node tree = imd.getAsTree("javax_imageio_gif_image_1.0"); 
        NodeList children = tree.getChildNodes(); 

        for (int j = 0; j < children.getLength(); j++) { 
         Node nodeItem = children.item(j); 
         NamedNodeMap attr = nodeItem.getAttributes(); 
         switch (nodeItem.getNodeName()) { 
          case "ImageDescriptor": 
           ImageDescriptor id = new ImageDescriptor(
             getIntValue(attr.getNamedItem("imageLeftPosition")), 
             getIntValue(attr.getNamedItem("imageTopPosition")), 
             getIntValue(attr.getNamedItem("imageWidth")), 
             getIntValue(attr.getNamedItem("imageHeight")), 
             getBooleanValue(attr.getNamedItem("interlaceFlag"))); 
           imageFrame.setImageDescriptor(id); 
           break; 
          case "GraphicControlExtension": 
           GraphicControlExtension gc = new GraphicControlExtension(
             DisposalMethod.find(getNodeValue(attr.getNamedItem("disposalMethod"))), 
             getBooleanValue(attr.getNamedItem("userInputFlag")), 
             getBooleanValue(attr.getNamedItem("transparentColorFlag")), 
             getIntValue(attr.getNamedItem("delayTime")) * 10, 
             getIntValue(attr.getNamedItem("transparentColorIndex"))); 
           imageFrame.setGraphicControlExtension(gc); 
           break; 
         } 
        } 
        frames.add(imageFrame); 
       } 
      } finally { 
      } 
     } 

     public BufferedImage getCurrentFrame() { 
      // If this was a optimised GIF, we would need to be 
      // merging frames together to produce the current frame 
      // This would then need to be reset each time we cycle... 
      return frames.isEmpty() ? null : frames.get(frame).getImage(); 
     } 

     public void play() { 
      if (!frames.isEmpty()) { 
       frame = 0; 
       playTimer.setDelay(frames.get(0).getGraphicControlExtension().getDelayTime()); 
       playTimer.start(); 
       player.repaint(); 
      } 
     } 

     public void stop() { 
      playTimer.stop(); 
     } 

     protected String getNodeValue(Node node) { 
      return node == null ? null : node.getNodeValue(); 
     } 

     protected int getIntValue(Node node) { 
      return node == null ? 0 : getIntValue(node.getNodeValue()); 
     } 

     protected boolean getBooleanValue(Node node) { 
      return node == null ? false : getBooleanValue(node.getNodeValue()); 
     } 

     protected int getIntValue(String value) { 
      return value == null ? 0 : Integer.parseInt(value); 
     } 

     protected boolean getBooleanValue(String value) { 
      return value == null ? false : Boolean.parseBoolean(value); 
     } 

     public class ImageFrame { 

      private BufferedImage image; 
      private ImageDescriptor imageDescriptor; 
      private GraphicControlExtension graphicControlExtension; 

      public ImageFrame(BufferedImage image) { 
       this.image = image; 
      } 

      protected void setImageDescriptor(ImageDescriptor imageDescriptor) { 
       this.imageDescriptor = imageDescriptor; 
      } 

      protected void setGraphicControlExtension(GraphicControlExtension graphicControlExtension) { 
       this.graphicControlExtension = graphicControlExtension; 
      } 

      public GraphicControlExtension getGraphicControlExtension() { 
       return graphicControlExtension; 
      } 

      public BufferedImage getImage() { 
       return image; 
      } 

      public ImageDescriptor getImageDescriptor() { 
       return imageDescriptor; 
      } 

     } 

     public class GraphicControlExtension { 

      private DisposalMethod disposalMethod; 
      private boolean userInputFlag; 
      private boolean transparentColorFlag; 
      private int delayTime; 
      private int transparentColorIndex; 

      public GraphicControlExtension(DisposalMethod disposalMethod, boolean userInputFlag, boolean transparentColorFlag, int delayTime, int transparentColorIndex) { 
       this.disposalMethod = disposalMethod; 
       this.userInputFlag = userInputFlag; 
       this.transparentColorFlag = transparentColorFlag; 
       this.delayTime = delayTime; 
       this.transparentColorIndex = transparentColorIndex; 
      } 

      public int getDelayTime() { 
       return delayTime; 
      } 

      public DisposalMethod getDisposalMethod() { 
       return disposalMethod; 
      } 

      public int getTransparentColorIndex() { 
       return transparentColorIndex; 
      } 

      public boolean isTransparentColorFlag() { 
       return transparentColorFlag; 
      } 

      public boolean isUserInputFlag() { 
       return userInputFlag; 
      } 

     } 

     public class ImageDescriptor { 

      private int imageLeftPosition; 
      private int imageTopPosition; 
      private int imageHeight; 
      private int imageWeight; 
      private boolean interlaced; 

      public ImageDescriptor(int imageLeftPosition, int imageTopPosition, int imageHeight, int imageWeight, boolean interlaced) { 
       this.imageLeftPosition = imageLeftPosition; 
       this.imageTopPosition = imageTopPosition; 
       this.imageHeight = imageHeight; 
       this.imageWeight = imageWeight; 
       this.interlaced = interlaced; 
      } 

      public int getImageHeight() { 
       return imageHeight; 
      } 

      public int getImageLeftPosition() { 
       return imageLeftPosition; 
      } 

      public int getImageTopPosition() { 
       return imageTopPosition; 
      } 

      public int getImageWeight() { 
       return imageWeight; 
      } 

      public boolean isInterlaced() { 
       return interlaced; 
      } 

     } 

    } 

} 

如果你想填它出來了,看看GIF Specifications ...

+0

感謝您的幫助! :) – user3320152

+0

太棒了... – alex2410

+0

@ alex2410這太瘋狂了...... – MadProgrammer