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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1466240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:35:17  来源:igfitidea点击:

How to set an image as a background for Frame in Swing GUI of java?

javaswing

提问by om.

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 ?

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

采纳答案by coobird

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.

中没有“背景图像”的概念JPanel,因此必须编写自己的方法来实现这样的功能。

One way to achieve this would be to override the paintComponentmethod to draw a background image on each time the JPanelis refreshed.

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

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

例如,可以将 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);
  }
}

(Above code has not been tested.)

(以上代码未经测试。)

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

以下代码可用于将 加入JPanelWithBackground到 a 中JFrame

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

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

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

回答by camickr

The Background Panelentry shows a couple of different ways depending on your requirements.

背景面板条目显示根据您的要求几个不同的方式。

回答by xrath

Here is another quick approach without using additional panel.

这是另一种不使用额外面板的快速方法。

JFrame f = new JFrame("stackoverflow") { 
  private Image backgroundImage = ImageIO.read(new File("background.jpg"));
  public void paint( Graphics g ) { 
    super.paint(g);
    g.drawImage(backgroundImage, 0, 0, null);
  }
};

回答by Boann

This is easily done by replacing the frame's content pane with a JPanel which draws your image:

这很容易通过用绘制图像的 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);
}

This example also sets the panel's layout to BorderLayout to match the default content pane layout.

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

(If you have any trouble seeing the image, you might need to call setOpaque(false)on some other components so that you can see through to the background.)

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

回答by dhaval joshi

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
  JButton b1;
  JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
 One way
-----------------*/
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\Users\Computer\Downloads\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);

// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\Users\Computer\Downloads  \colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
  setSize(399,399);
   setSize(400,400);
   }
   public static void main(String args[])
  {
   new BackgroundImageJFrame();
 }
 }

回答by ThilinaMD

if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator

如果您使用的是 netbeans,您可以向框架添加 jlabel,并通过属性将其图标更改为您的图像并删除文本。然后通过导航器将 jlabel 移动到 Jframe 或任何内容窗格的底部

回答by Ankit Sharma

Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components. enter image description here

也许最简单的方法是添加图像、缩放它并将其设置为 JFrame/JPanel(在我的情况下为 JPanel),但请记住只有在添加其他子组件后才将其“添加”到容器中。 在此处输入图片说明

    ImageIcon background=new ImageIcon("D:\FeedbackSystem\src\images\background.jpg");
    Image img=background.getImage();
    Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
    background=new ImageIcon(temp);
    JLabel back=new JLabel(background);
    back.setLayout(null);
    back.setBounds(0,0,500,600);