Reputation: 3381
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.
Upvotes: 3
Views: 4909
Reputation: 109815
..I want to move it a later stage. But right now I want it to show first :)
There are two ways,
Put JLabel car
to JPanel
, drawing an Image
by using paintComponent
, instead of JLabel background
(advantage JPanel
is container with proper notifications for LayoutManager
).
Put JLabel car
to JLabel background
, but JLabel
haven't implemented any LayoutManager
, have to set desired.
JLabel
are static, with zero CPU and GPU inpact ad consumption in compare with paintComponent
. JLabel
isn't container and with proper notifications for LayoutManager
, required a few code lones moreover in compare with JLabel
placed in JPanel
, for movement (AbsoluteLayout) is quite good solution.Draw both Images
by using BufferedImage and Graphics.
Upvotes: 4
Reputation: 3327
Add them both to a JPanel that uses OverlayLayout. It is not ok to add a JLabel
to another JLabel
.
This code has not gone through a compiler so take it for what it is :)
JPanel panel = new JPanel(new OverlayLayout());
panel.add(background);
panel.add(car);
Upvotes: 3
Reputation: 3381
Works.. Added the following to make it display:
car.setBounds(200, 200, 200, 200);
Apparently it's because by default a null layout manager is used. So setting the bounds of the label will enable it to display since the default size is 0.
Upvotes: 0