如何在另一个运动图像下添加背景图像?

时间:2014-04-23 15:37:40

标签: java image user-interface jframe

我正在研究空中交通管制系统项目,我想让飞机在我的地图上移动。 到目前为止,我设法让图像移动(平面),现在我想在下面添加背景图像(地图)。我怎么做?

这是我的代码:

public class AnimatedPlane extends JFrame {

    public static void main(String[] args) {
        AnimatedPlane animatedplane = new AnimatedPlane();
    }

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

                JFrame frame = new JFrame("Plane");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new AnimationPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class AnimationPane extends JPanel {


        private BufferedImage plane;
        private int xPos = 0;
        private int direction = 1;

        public AnimationPane() {
            try {
                plane = ImageIO.read(new File("H:\\Documents\\NetBeansProjects\\GroupProject\\src\\groupproject\\plane.png"));
                Timer timer;
                timer = new Timer(40, new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {
                  xPos += direction;
                  if (xPos + plane.getWidth() > getWidth()) {
                      xPos = getWidth() - plane.getWidth();
                      direction *= -1;
                  } else if (xPos < 0) {
                      xPos = 0;
                      direction *= -1;
                  }
                  repaint();
              } 

          });
                timer.setRepeats(true);
                timer.setCoalesce(true);
                timer.start();
            } catch (IOException ex) {
            }


        }

        @Override
        public Dimension getPreferredSize() {
            return plane == null ? super.getPreferredSize() : new Dimension(plane.getWidth() * 4, plane.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            int y = getHeight() - plane.getHeight();
            g.drawImage(plane, xPos, y, this);

        }

    }

}

1 个答案:

答案 0 :(得分:1)

你不必在“下面”实际绘制它。 您可以先绘制背景,然后绘制所有平面(它们的图像)。

像:

g.drawImage(myBackground, xPos, yPos, this); //Note: xPos and yPos is normally 0 in the beginning, as long as you dont move the map background around

g.drawImage(plane, xPos, yPos, this);

它基本上总是这样:

  1. 画背景。
  2. 绘制应该在背景上(“上方”)的任何对象。