如何创建重叠的背景和前景图像?
通过使用Java swing,有什么可用的方法来创建可在静态 背景图像上移动的前景
图像(例如骑士图像)?
我们可以JLabel
使用图像图标吗?
-
该解决方案还解决中提到的问题:图像在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 codes:
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); } }); } }