Setting background images in JFrame

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

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

4条回答
  •  囚心锁ツ
    2020-11-22 16:21

    There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is:

    1. Create a subclass of JComponent.
    2. Override the paintComponent(Graphics g) method to paint the image that you want to display.
    3. Set the content pane of the JFrame to be this subclass.

    Some sample code:

    class ImagePanel extends JComponent {
        private Image image;
        public ImagePanel(Image image) {
            this.image = image;
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, this);
        }
    }
    
    // elsewhere
    BufferedImage myImage = ImageIO.read(...);
    JFrame myJFrame = new JFrame("Image pane");
    myJFrame.setContentPane(new ImagePanel(myImage));
    

    Note that this code does not handle resizing the image to fit the JFrame, if that's what you wanted.

提交回复
热议问题