如何在java的Swing GUI中将图像设置为Frame的背景? [英] How to set an image as a background for Frame in Swing GUI of java?

查看:31
本文介绍了如何在java的Swing GUI中将图像设置为Frame的背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Java 的 Swing 创建了一个 GUI.我现在必须将一个 sample.jpeg 图像设置为我放置组件的框架的背景.如何做到这一点?

I have created one GUI using Swing of Java. I have to now set one sample.jpeg image as a background to the frame on which I have put my components.How to do that ?

推荐答案

JPanel,因此必须编写自己的方式来实现这样的功能.

There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

实现这一目标的一种方法是覆盖 paintComponent 方法在每次 JPanel 刷新时绘制背景图像.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

例如,一个JPanel的子类,并添加一个字段来保存背景图像,并覆盖paintComponent方法:

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);
  }
}

(以上代码未经测试.)

(Above code has not been tested.)

以下代码可用于将 JPanelWithBackground 添加到 JFrame 中:

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

在这个例子中,ImageIO.read(File)方法用于读取外部JPEG文件.

In this example, the ImageIO.read(File) method was used to read in the external JPEG file.

这篇关于如何在java的Swing GUI中将图像设置为Frame的背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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