Home > Software engineering >  Im triying to use a JLabel as a BackGround and I cant
Im triying to use a JLabel as a BackGround and I cant

Time:01-23

            f = new JFrame();
    f.setExtendedState(JFrame.MAXIMIZED_BOTH);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    
    d = new JPanel();
    f.add(d);
    ImageIcon icon = new ImageIcon("C:\\Users\\jean\\Pictures\\988057.jpg");
    JLabel background = new JLabel(icon);
    background.setSize(d.getSize());
    background.setLocation(0,0);
    d.add(background);
    d.setLayout(null);
    background.setOpaque(true);

    d.add(background, BorderLayout.CENTER, 0);

Im triying to put a JLabel as a BackGround but I cant. the path its all right. what happening?

CodePudding user response:

You are calling f.setVisible(true), before adding label and icons to it. And you don't want to add panel in between label and fram. You can try this approach,

            f = new JFrame();
            f.setExtendedState(JFrame.MAXIMIZED_BOTH);

            f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

            ImageIcon icon = new ImageIcon("C:\\Users\\jean\\Pictures\\988057.jpg");
            JLabel background = new JLabel();
            background.setIcon(icon);

            background.setSize(f.getSize());
            f.add(background);
            f.setVisible(true);

I hope this will solve your problem.

CodePudding user response:

The Solution. Thanks Guys.

    f = new JFrame();
    f.setExtendedState(JFrame.MAXIMIZED_BOTH);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    
    d = new JPanel();
    d.setSize(f.getSize());
    f.add(d);   
    
    File file = new File("C:\\Users\\jean\\Pictures\\988057.jpg");

    
    try {
        
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
        label.setSize(d.getSize());
        d.add(label);
        
    } catch (IOException e) {
        e.printStackTrace();
        
    }
  •  Tags:  
  • java
  • Related