Java 相互显示图像并移动它

Java displaying images on one another and move it

我是 Java,

的初学者

而且我必须构建一个程序来在海上移动船只。

我的想法是插入一张图片作为背景屏幕,然后放置另一张代表船的图片。

我不知道怎么做。

如何把一张图片放在所有的Jframe上作为背景图片, 以及如何放置另一张图片,以及如何在此背景上移动第二张图片

谢谢。

您可以使用 Draggable 让您的船可以拖动

Image background = ...;
Image boat = ...;
JPanel bgPanel = new JPanel() {
  public void paintComponent(Graphics g) {
     g.drawImage(background,0,0,null);
  }
}
JLabel boatLbl = new JLabel(new ImageIcon(boat));
bgPanel.setLayout(null);
new Draggable(boatLbl);
bgPanel.add(boatLbl);

How can put an image on all the Jframe as a background image,...

避免考虑 JFrame,您的 Swing GUI 工作应该集中于创建和使用 JPanel。然后可以在 JFrame(或 JDialog,或另一个 JPanel,或...)中显示。通过在 JPanel 的 paintComponent(Graphics g) 方法中调用 g.drawImage(myImage, 0, 0, null),可以很容易地在 JPanel 中显示背景图像。

and how can i put over another image, and how can i move the second image on this background

  1. 只需使用在相同 paintComponent(Graphics g) 方法中绘制的第二个 BufferedImage,但在绘制第一个图像之后。您将使用相同的 g.drawImage(mySprite, x, y, null),但会使用字段(此处为 x 和 y)来更改精灵图像的位置。更改通常发生在 Swing Timer 中。
  2. 或者您可以在 JLabel 中显示的 ImageIcon 中显示 sprite 图像,并在您的 Swing Timer 中移动 JLabel 的位置。

编辑 你问:

How can i resize a picture because when i insert it it take all of the frame?

最好创建一个新的 BufferedImage,一个你想要的大小,从新图像中获取一个 Graphics 对象,使用该 Graphics 对象将原始图片绘制到新图像中,然后 drawImage(...) 允许重新调整大小的重载,然后处理 Graphics 对象。例如

  double scale = 0.5; // make it half as wide and high as big image
  int smallImageWidth = (int) (bigImage.getWidth() * scale);
  int smallImageHeight = (int) (bigImage.getHeight() * scale);

  BufferedImage smallImage = new BufferedImage(smallImageWidth, smallImageHeight, BufferedImage.TYPE_INT_ARGB);
  // get a Graphics object from this image
  Graphics g = smallImage.getGraphics();

  // draw in the large image, scaling it
  g.drawImage(bigImage, 0, 0, smallImageWidth, smallImageHeight, null);

  // get rid of the Graphics object to save resources
  g.dispose(); // never do this with Graphics objects given you by the JVM