JPanel动画背景

时间:2013-04-11 03:38:57

标签: java swing animation background jpanel

这是一个非常普遍的问题,但我应该如何为JPanel添加动画背景。我希望背景能够支持所有面板的组件和图形。现在,我有两个单独的类(一个用于主面板,另一个用于背景)。 background类使用repaint()为在屏幕上移动的网格设置动画。我试图让主面板背景透明,但这并没有让我到处都是。

更多信息: 我的主面板是CardLayout的一部分,它有许多不同的类。因此,当我将主面板添加到主框架时,我正在进行frame.getContentPane().add(cards, BorderLayout.CENTER)

cards是一个JPanel,它充当主面板和主面板内所有面板的容器。

有人可以帮助我获得面板动画背景吗?

2 个答案:

答案 0 :(得分:2)

您可以使用Toolkit.getImage()加载动画图像,然后在容器的paintComponent中绘制图像。确保ImageObserver已设置(非空)以便正确更新动画帧。有关如何加载,观察和更新图像的详细信息,请参阅 Java AWT参考中的How Images are Loaded附录。

这是一个简单的例子:

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class AnimatedPanelDemo {
    static class ImagePanel extends JPanel {
        private Image image;
        ImagePanel(Image image) {
            this.image = image;
        }
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image,0,0,getWidth(),getHeight(),this);
        }
    }

    private static void createAndShowUI() {
        try {
            JFrame frame = new JFrame("Image");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);

            Image image = Toolkit.getDefaultToolkit().getImage(new URL(
                    "http://duke.kenai.com/iconSized/duke.running.gif"));

            ImagePanel imagePanel = new ImagePanel(image);

            imagePanel.add(new JLabel("Some label"));
            frame.add(imagePanel);
            frame.setSize(100, 100);
            frame.setVisible(true);
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

答案 1 :(得分:0)

好吧,这是我对stackoverflow的第一个答案。

将尝试通过这种复杂的AWT和Swift API帮助我学习。

下面是扩展JFrame的构造器

package xpto;

import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.awt.image.ImageObserver;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import sun.java2d.SunGraphicsEnvironment;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class FrameLuckyRaffle extends JFrame {

    /**
     * 
     */
    private JLabel backgroundLabel;
    private ImageIcon imageIcon;
    private Image bgImage;


    /**
     * Constructor of this frame.
     */
    public FrameLuckyRaffle(String background, final String dbname) {
        try {
            setTitle("Lucky Raffle of "+ dbname);

            GraphicsConfiguration config = this.getGraphicsConfiguration();
            Rectangle usableBounds = SunGraphicsEnvironment.
                                     getUsableBounds(config.getDevice());
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setBounds(100, 100, (int)(usableBounds.getWidth()*0.8), 
                                (int)(usableBounds.getHeight()*0.8));
            setMinimumSize(new Dimension(1024, 700));
            setResizable(true);
            setDefaultLookAndFeelDecorated(true);

            backgroundLabel = new JLabel() {
               public void paintComponent(Graphics g) {
            // alternative --> g.drawImage(bgImage, 0, 0, null);
            // I prefer to control the new ImageObserver parameter as bellow
                    g.drawImage(bgImage, 0, 0, new ImageObserver() {
                    @Override
                    public boolean imageUpdate(Image img, int infoflags, 
                                               int x, int y, int width, int height) {
                        img.getScaledInstance(getWidth(),getHeight(),
                                              Image.SCALE_FAST);
                        return true;
                    }
               });
           // this is used to have easier control on 
           // image manipulation on my application
              Graphics2D g2d = (Graphics2D)g; 
              super.paintComponent(g2d);
              revalidate();
              repaint();
          }
      };
      backgroundLabel.setBounds(0, 0, 0, 0);
      // this is necessary if you want more child 
      // components to be visible on the JFrame afterwards
      backgroundLabel.setOpaque(false);  
      setContentPane(backgroundLabel);

      addWindowListener(new WindowListener() {
          @Override
          public void windowOpened(WindowEvent e) {
        // Set Frame Background
             imageIcon = new ImageIcon(Toolkit.getDefaultToolkit().
                        createImage(FrameBusinessPure.class.getResource(background)));
             bgImage = imageIcon.getImage().
                       getScaledInstance(getWidth(),getHeight(), Image.SCALE_FAST);
          }
        // Even after closing the window, JVM didn't Garbage Collected the instanced
        // objects, for some reason. Forcing the objects to null helped on that.
          @Override
          public void windowClosed(WindowEvent e) {
              backgroundLabel = null;
              imageIcon = null;
              bgImage = null;
              System.gc();
          }
      });

      addWindowStateListener(new WindowStateListener() {
          @Override
          public void windowStateChanged(WindowEvent e) {

        // if you flush the object on runtime you will surpass the
        // memory leak on using GIFs and most complex graphics

              bgImage.flush();
              bgImage = imageIcon.getImage().
                        getScaledInstance(getWidth(),getHeight(), Image.SCALE_FAST);
          }
       });

    addMouseMotionListener(new MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent e) {

      // if you flush the object on runtime you will surpass the
      // memory leak on using GIFs and most complex graphics

           bgImage.flush();
           bgImage = imageIcon.getImage().
                     getScaledInstance(getWidth(),getHeight(), Image.SCALE_FAST);
       });
       }catch (Exception e) {
           e.printStackTrace();
       }
    }
}

随时可以在下面的链接中了解更多信息

https://www.oracle.com/java/technologies/painting.html