如何将更多图像添加到背景Jpanel?

时间:2015-02-26 21:20:11

标签: java swing

package Main;

import javax.swing.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.io.File;
import java.io.IOException;


public class Background {

    public static void main(String[] args) {

        //Window Name
        JFrame F = new JFrame("Xiao's World");

        //Background Image
        try{
            F.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("src/Main/sky.jpg")))));

        }catch(IOException e)
        {
            //Case if image is not available
            System.out.println("Image doesn't exist.");
        }

        //Frame setup and rules
        F.setResizable(false);
        F.pack();
        F.setSize(800, 600);
        F.setVisible(true);

    }
}

你看我可以很容易地显示背景没有问题,但是我希望在这个背景上显示一张图片以及其他一些图片是否有办法轻松地将多个图像叠加在一起?

我试图创建一个场景,但它有点困难,因为大多数教程都是背景成像,而不是场景制作。此外,如果你可以帮助我,所以我可以设置一个音乐流,单独使用它,这将是伟大的,我有图像和文件,我只需要一个代码,以帮助我设置它。我对方法不太满意,所以我很感激解释。

1 个答案:

答案 0 :(得分:2)

  • 使用JPanel
  • 之类的内容创建自定义组件
  • 覆盖它的paintComponent方法。
  • 使用List维护图像的z排序,并使用Graphics#drawImage
  • 将它们绘制到组件中

有关详细信息,请参阅Painting in AWT and SwingPerforming Custom Painting

您还需要查看2D Graphics,以便更好地了解如何与Graphics上下文进行互动。

虽然默认情况下Swing是双缓冲的,但它使用被动渲染引擎,这意味着UI的更新由其自行决定。

最终,您需要控制渲染过程,以便在需要更新时更新UI,为此,您需要查看BufferingStrategy。您可以通过查看BufferStrategy and BufferCapabilitiesBufferStrategy JavaDocs

了解更多信息

使用...

Sky Mountains Tree

以下代码可以生成......

enter image description here

这只会生成一个随机点,可以在场景中添加0-1000棵树......

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Test{

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

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

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

    public class TestPane extends JPanel {

        private BufferedImage sky, mountains, tree;
        private List<Point> treePoints;

        public TestPane() {
            try {
                sky = ImageIO.read(getClass().getResource("/Sky.png"));
                mountains = ImageIO.read(getClass().getResource("/Mountians.png"));
                tree = ImageIO.read(getClass().getResource("/Tree.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            treePoints = new ArrayList<>(25);

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.anchor = gbc.SOUTH;

            JSlider slider = new JSlider(0, 1000);
            slider.setValue(0);
            add(slider, gbc);
            slider.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    int count = slider.getValue();
                    if (count == 0) {
                        treePoints.clear();
                    } else if (count < treePoints.size()) {
                        treePoints = treePoints.subList(0, count - 1);
                    } else {

                        Rectangle skyBounds = getSkyBounds();
                        int y = (skyBounds.y + skyBounds.height) - tree.getHeight();
                        while (treePoints.size() < count) {

                            int x = skyBounds.x + (int)Math.round((Math.random() * (skyBounds.width + tree.getWidth()))) - tree.getWidth();
                            treePoints.add(new Point(x, y));

                        }

                    }
                    repaint();
                }
            });
        }

        protected Rectangle getSkyBounds() {

            int x = (getWidth() - sky.getWidth()) / 2;
            int y = (getHeight() - sky.getHeight()) / 2;

            return new Rectangle(x, y, sky.getWidth(), sky.getHeight());

        }

        @Override
        public Dimension getPreferredSize() {
            return sky == null ? new Dimension(200, 200) : new Dimension(sky.getWidth(), sky.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            Rectangle skyBounds = getSkyBounds();

            g2d.drawImage(sky, skyBounds.x, skyBounds.y, this);
            g2d.drawImage(mountains, 
                            skyBounds.x, 
                            skyBounds.y + skyBounds.height - (mountains.getHeight()), 
                            this);

            for (Point p : treePoints) {
                g2d.drawImage(tree, p.x, p.y, this);
            }

            g2d.dispose();
        }

    }

}