如何创建重叠的背景和前景图像?

时间:2016-02-29 23:32:44

标签: java swing

通过使用Java swing,可以使用哪种方法来创建可在静态背景图像上移动的前景图像(例如 骑士 的图像)?

我们应该将JLabel与图片图标一起使用吗?

1 个答案:

答案 0 :(得分:3)

此解决方案还解决了以下问题:Images In JFrame are overwriting each other not displaying both images over eachother

如果我们尝试添加背景和一些前景图像,如果我们打算让这些图像相互重叠可能会有点棘手,因为Java提供的许多布局可能会阻止组件(例如JLabel)相互重叠。将图像定位到确切的位置也是一个问题。

当我们想要创建一个类似于我们在游戏中看到的屏幕时,我会建议一种不同的方法:

enter image description here

不是创建多个填充了imageIcon的JLabel,而是直接在面板上绘制替代方案。这是一个自定义面板,包含我们有兴趣绘制的图像实例。

class DrawingSpace extends JPanel
{
    private BufferedImage bg, hero;
    private int bgWidth, bgHeight;
    private int heroWidth, heroHeight;  
    private int scWidth, scHeight;
    private int mouseX, mouseY;

    public DrawingSpace(){      
        loadImages();
        init();     
        setPreferredSize(new Dimension(scWidth, scHeight));     
        addMouseMotionListener(new MouseHandler());     
    }

    private void init(){
        mouseX = 0;
        mouseY = 0;
        heroWidth = hero.getWidth();
        heroHeight = hero.getHeight();      
        bgWidth = bg.getWidth();
        bgHeight = bg.getHeight();      
        scWidth = bgWidth;
        scHeight = bgHeight;        
    }

    private void loadImages(){
        try{
            bg = ImageIO.read(getClass().getResource("Images/background.jpg"));
            hero = ImageIO.read(getClass().getResource("Images/knight.png"));
        }catch(IOException ioe){System.out.println("Unable to open file");}
    }

    @Override public void paintComponent(Graphics g){
        super.paintComponent(g);        
        g.drawImage(bg, 0, 0, bgWidth, bgHeight, null);
        g.drawImage(hero, mouseX-(heroWidth/2), mouseY-(heroHeight/2), heroWidth, heroHeight, null);        
    }

    private class MouseHandler implements MouseMotionListener
    {
        @Override public void mouseMoved(MouseEvent e){
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();
        }
        @Override public void mouseDragged(MouseEvent e){}  
    }
}

用于驱动代码的跑步者类:

class KnightRunner
{   
    public static void main(String[] args){

        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                JFrame frame = new JFrame("Knight Runner");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
                frame.add(new DrawingSpace());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);             
            }
        });
    }       
}