在JFrame中设置背景图像

36 java swing background image jframe

是否有任何方法可以将图像设置为背景JFrame

Mic*_*ers 39

没有内置方法,但有几种方法可以做到.我目前最直接的想法是:

  1. 创建一个子类JComponent.
  2. 重写paintComponent(Graphics g)方法以绘制要显示的图像.
  3. 设置内容窗格JFrame是这个子类.

一些示例代码:

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));
Run Code Online (Sandbox Code Playgroud)

请注意,此代码不会处理调整图像大小以适应JFrame,如果这是您想要的.

  • 您应该使用super.paintComponents()方法来painComponent方法. (2认同)

Sav*_*sis 19

试试这个 :

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这将导致内容窗格不是容器.如果要向其添加内容,则必须子类化JPanel并覆盖paintComponent方法.


cam*_*ckr 6

您可以使用Background Panel类.它执行如上所述的自定义绘制,但为您提供显示缩放,平铺或正常大小的图像的选项.它还说明了如何将带有图像的JLabel用作框架的内容窗格.