我正在开发一个 Java 项目来模拟直升机在框架中的飞行。直升机使用箭头键在屏幕上移动。我希望直升机能够无限移动,即当直升机到达画面边缘时,背景应该向相反的方向移动,以产生无尽地形的效果。
这是我到目前为止的代码:
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainFrame extends JFrame
{
private static int FRAME_WIDTH = 800;
private static int FRAME_HEIGHT = 500;
public MainFrame()
{
add(new AnotherBackground(FRAME_WIDTH, FRAME_HEIGHT));
setTitle("Helicopter Background Test");
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new MainFrame();
}
}
class AnotherBackground extends JPanel
{
private BufferedImage heliImage = null;
private BufferedImage backImage = null;
private int heliX = 0;
private int heliY = 0;
private int backX = 0;
private int backY = 0;
private int frameWidth = 0;
private int frameHeight = 0;
private int backWidth = 0;
private int backHeight = 0;
public AnotherBackground(int fWidth, int fHeight)
{
frameWidth = fWidth;
frameHeight = fHeight;
this.setFocusable(true);
this.addKeyListener(new HeliListener());
try
{
heliImage = ImageIO.read(new URL("http://imageshack.us/a/img7/2133/helicopter2f.png"));
// 2.7 Meg Crap that is a humungous image! Substitute dummy.
backImage = new BufferedImage(1918,1200,BufferedImage.TYPE_INT_RGB);
}
catch(IOException ex)
{
System.out.println("Problem durinng loading heli image");
}
backWidth = backImage.getWidth();
backHeight = backImage.getHeight();
HeliPainter l = new HeliPainter();
new Thread(l).start();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backImage, backX, backY, null);
g.drawImage(heliImage, heliX, heliY, null);
}
class HeliListener extends KeyAdapter
{
@Override
public void keyPressed(KeyEvent e)
{
System.out.println(heliX + " " + heliY + " " + backX + " " + backY);
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(heliX > 0)
{
heliX -= 5;
}
else
{
backX += 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(heliX < frameWidth)
{
heliX += 5;
}
else
{
backX -= 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
if(heliY > 0)
{
heliY -= 5;
}
else
{
backY += 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(heliY < frameHeight)
{
heliY += 5;
}
else
{
backY -= 5;
}
}
}
}
class HeliPainter implements Runnable
{
@Override
public void run()
{
try
{
while(true)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
repaint();
}
});
Thread.sleep(1);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem putting thread to sleep");
}
}
}
}
现在代码中有两个图像。一个是小型直升机,另一个是大型(2.7 兆)背景。他们在这里:
如何连续显示BG?