如何在java的Swing GUI中将图像设置为Frame的背景?

om.*_*om. 12 java swing

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

coo*_*ird 21

在a中没有"背景图像"的概念JPanel,因此必须编写自己的方式来实现这样的特征.

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

例如,可以将a子类化JPanel,并添加一个字段来保存背景图像,并覆盖该paintComponent方法:

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

(以上代码尚未经过测试.)

可以使用以下代码将其添加JPanelWithBackgroundJFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));
Run Code Online (Sandbox Code Playgroud)

在此示例中,该ImageIO.read(File)方法用于读取外部JPEG文件.

  • 这并不能完全回答问题。它将背景图像放在面板上,但随后只是将面板插入到正常布局中。问题是如何在其他组件后面的框架上设置背景。 (2认同)

Boa*_*ann 5

通过使用绘制图像的JPanel替换框架的内容窗格可以轻松完成此操作:

try {
    final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
    setContentPane(new JPanel(new BorderLayout()) {
        @Override public void paintComponent(Graphics g) {
            g.drawImage(backgroundImage, 0, 0, null);
        }
    });
} catch (IOException e) {
    throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)

此示例还将面板的布局设置为BorderLayout以匹配默认内容窗格布局.

(如果您在查看图像时遇到任何问题,可能需要调用setOpaque(false)其他一些组件,以便可以看到背景.)