在JFrame中设置背景图片 [英] Setting background images in JFrame

查看:185
本文介绍了在JFrame中设置背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可用于将图像设置为背景的任何方法的JFrame

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

推荐答案

有没有内置的方法,但有几个方法可以做到这一点。我可以在此刻想到的最简单的方法是:

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. 创建的子类<一href=\"http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html\"><$c$c>JComponent.

  2. 重写<一个href=\"http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)\"><$c$c>paintComponent(Graphics G) 方法来作画要显示的图像。

  3. Set内容窗格中的的JFrame 是这样的子类。

  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.

一些示例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.load(...);
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));

请注意,这code不处理调整图像大小以适合的JFrame ,如果这就是你想要的。

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

这篇关于在JFrame中设置背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆