简体   繁体   English

如何在Java中将图像彼此叠加

[英]How to place images on top of each other in java

I have a background image of a road, which I have displayed on a JFrame using an ImageIcon. 我有一条道路的背景图像,已使用ImageIcon将其显示在JFrame上。 I want to put a car on top of that background image at a certain (x,y) location. 我想将汽车放在特定(x,y)位置的背景图像上。

I tried using another ImageIcon and the background does not appear when I run the program , however the car does. 我尝试使用其他ImageIcon,但运行该程序时背景不出现,但是汽车却显示了。

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JLabel;

public class Gui extends JFrame {

private ImageIcon northcar = new ImageIcon("src/north.gif");
private ImageIcon usIcon = new ImageIcon("src/trafficLight.jpg");


public Gui() {
    add(new JLabel(usIcon)); // background image does not appear after the i added the northcar label
    add(new JLabel(northcar)); // this picture can be seen 


}

public static void main(String[] args) {


    Gui frame = new Gui();
    frame.setTitle("TestImageIcon");
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(0, 0, 650, 650);
    frame.setVisible(true);

}
}

I heard about using a canvas but have no clue. 我听说过要使用画布,但一无所知。 Any ideas ? 有任何想法吗 ?

Many Thanks 非常感谢

如何使用LayeredPane可能帮助。

add(new JLabel(usIcon)); 
add(new JLabel(northcar)); 

Change the order to: 将顺序更改为:

add(new JLabel(northcar)); 
add(new JLabel(usIcon)); 

Read up on Z-Order. 阅读Z顺序。 Simply the last component added gets painted first. 只需添加最后一个组件即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM