Setting background images in JFrame

后端 未结 4 1415
余生分开走
余生分开走 2020-11-22 15:49

Are any methods available to set an image as background in a JFrame?

4条回答
  •  一个人的身影
    2020-11-22 16:07

    Try this :

    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    
    public class Test {
    
        public static void main(String[] args) {
            JFrame f = new JFrame();
            try {
                f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
            } catch (IOException e) {
                e.printStackTrace();
            }
            f.pack();
            f.setVisible(true);
        }
    
    }
    

    By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

提交回复
热议问题