I have the following code:
try {
File file_background = new File(
"C:\\Users\\xxxx\\Desktop\\background.png");
ImageIcon icon_background = new ImageIcon(
ImageIO.read(file_background));
JLabel background = new JLabel(icon_background);
window.setContentPane(background);
File file_car = new File(
"C:\\Users\\xxxxxx\\Desktop\\car.png");
ImageIcon icon_car = new ImageIcon(ImageIO.read(file_car));
JLabel car = new JLabel(icon_car);
car.setVisible(true);
background.add(car);
// TODO Get car showing on top of the background label
} catch (IOException e) {
e.printStackTrace();
}
Where I’m attempting to have the car label show on TOP of the background label. But I’m only getting the background JLabel showing. I’m new to SWING so any suggestions to what steps I’m missing would be great.
There are two ways,
1st.
Put
JLabel cartoJPanel, drawing anImageby usingpaintComponent, instead ofJLabel background(advantageJPanelis container with proper notifications forLayoutManager).Put
JLabel cartoJLabel background, butJLabelhaven’t implemented anyLayoutManager, have to set desired.JLabelare static, with zero CPU and GPU inpact ad consumption in compare withpaintComponent.JLabelisn’t container and with proper notifications forLayoutManager, required a few code lones moreover in compare withJLabelplaced inJPanel, for movement (AbsoluteLayout) is quite good solution.2nd.
Draw both
Imagesby using BufferedImage and Graphics.