0

I'm wondering how to add my JPanel image into the JFrame with my current code. I know that I have the Jframe working but I need the Panel to show my image so that then I can set multiple overlapping images in the same JFrame. How do I do this by altering my current code?

import javax.imageio.*;
import javax.swing.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.awt.FlowLayout;
import java.awt.Dimension;


public class Background {
    public Background(JFrame frame) throws IOException{
        BufferedImage castles = ImageIO.read 
        (newFile("C:/Users/dude42/Documents/game/castles.png"));
    JLabel label = new JLabel(); 

    label.setLocation(0,0);
    label.setIcon(new ImageIcon(castles));

    frame.add(label);  
    frame.setVisible(true);
    frame.setSize(1080,1080);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


    JPanel pane0 = new JPanel();
    pane0.setPreferredSize(new Dimension(1080, 1080));
    pane0.setLayout(null);
    pane0.add(label,0);
    pane0.setVisible(true);


}

public static void main(String avg[]) throws IOException{
    JFrame frame = new JFrame();
    Background background = new Background(frame);
}

}

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. 3) If it were just a single image, it could be .. – Andrew Thompson Apr 27 '17 at 17:26
  • .. displayed in a `JLabel`, but since it requires multiple overlapping images, it would be better to either custom paint a panel, or paint them all to a single image and display that in a `JLabel`. For the first way, see.. [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/). 4) Voting to close as 'too broad'. – Andrew Thompson Apr 27 '17 at 17:28
  • A component needs a size, understand, that once you remove the `LayoutManager`s, you become responsible for it's job, so things like `preferredSize` won't work any more. Also, you need to add the panel to the frame (before you make it visible) – MadProgrammer Apr 27 '17 at 21:44
  • I see, that should help. – Scott Field Apr 28 '17 at 18:23

0 Answers0