Home > Enterprise >  How to show a backround image in JFrame? [duplicate]
How to show a backround image in JFrame? [duplicate]

Time:09-17

I am trying try to put image on this button but I can't understand what wrong with this.

public class LabelBackground {

private static final long serialVersionUID = 1L;
static JFrame frame;
static JPanel panel;

public static void main(String[] args) {
    LabelBackground u = new LabelBackground();
    frame.setVisible(true);
}

public LabelBackground() {
    frame = new JFrame("hi");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600,600);
    frame.setResizable(false);
    ImagePanel img = new ImagePanel("C:\\Users\\yoyos\\Downloads\\funny_picture.jpg");      
    JButton b1 = new JButton("test");
    frame.add(img);
    frame.add(b1);
}
}

class ImagePanel extends JPanel {

    private BufferedImage image;
    
    public ImagePanel(String img) {
       try {                
          image = ImageIO.read(new File(img));
       } catch (IOException ex) {
            System.out.println("Error1***************");
       }
    }

    @Override
    protected void paintComponent(Graphics g) {
         super.paintComponent(g);
        g.drawImage(image, 0, 0,600,600,this);
    }
}

CodePudding user response:

Here is your soloution. Don't forget to put the picture in the project space. If your putting the picture in other folder then in the ImageIcon image = new ImageIcon("./folderName/imageName.png"); specify your folder name and your image name. Check for the .png or .jpg format also. Check the size of the frame with your image. That's it.

Thank you


JFrame frame = new JFrame();

ImageIcon image = new ImageIcon("MainScreen.png");

public Gui() {

    JLabel label = new JLabel(image);
    label.setBounds(0, 0, 1280, 675);

    frame.setTitle("Gui");
    frame.setSize(1280, 675);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(label);

    frame.setVisible(true);

}

public static void main(String args[]) {
    new Gui();
}

  • Related