How to set Jframe Background Image in GroupLayout Java

前端 未结 3 380
春和景丽
春和景丽 2021-01-23 06:26

Am trying to set a background image for my frame but it does not work. I tried this link:

Setting background images in JFrame

The code:

setConten         


        
3条回答
  •  花落未央
    2021-01-23 07:07

    The basic concept looks fine.

    The only possible reason you might be getting problems is if the image doesn't exist.

    It looks look you are trying to reference an image that should exist within the context of the Jar

    Instead of

    ImageIO.read(new File("/Images/about.png"))
    

    Try

    ImageIO.read(getClass().getResource("/Images/about.png"))
    

    Instead.

    Also, don't swallow exceptions, make sure all exceptions are been logged at the very least

    enter image description here

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.HeadlessException;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class BackgroundFrameImage {
    
        public static void main(String[] args) {
            new BackgroundFrameImage();
        }
    
        public BackgroundFrameImage() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    try {
                        JLabel label = new JLabel(new ImageIcon(ImageIO.read(...))));
    
                        JFrame frame = new JFrame("Testing");
                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        frame.setContentPane(label);
                        frame.setLayout(new BorderLayout());
                        JLabel text = new JLabel("Hello from the foreground");
                        text.setForeground(Color.WHITE);
                        text.setHorizontalAlignment(JLabel.CENTER);
                        frame.add(text);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);
                    } catch (IOException | HeadlessException exp) {
                        exp.printStackTrace();
                    }
                }
            });
        }
    
    }
    

提交回复
热议问题