栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

该解决方案还解决中提到的问题:图像在Jframe的是覆盖彼此不显示在两个图像海誓山盟

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

与其创建多个装满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){}      }}

A runner class to drive the pres:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号