开发者

How to place images on top of each other in java

开发者 https://www.devze.com 2023-01-04 02:22 出处:网络
I have a background image of a road, which I have displayed on a JFrame using an ImageIcon. I want to put a car on top of that background image at a certain (x,y) location.

I have a background image of a road, which I have displayed on a JFrame using an ImageIcon. I want to put a car on top of that background image at a certain (x,y) location.

I tried using another ImageIcon and the background does not appear when I run the program , however the car does.

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 ImageI开发者_C百科con 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


How about using LayeredPane, this might help.


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. Simply the last component added gets painted first.

0

精彩评论

暂无评论...
验证码 换一张
取 消