java - 将图像设置为 JFrame 的背景

标签 java swing jframe

我正在制作一个小应用程序,但我想将图像设置为整个窗口的背景。我试着像下面那样做,但什么也没发生。该图像位于类(class)所在的文件夹中,因此我只输入了名称...您能帮帮我吗?我能做什么?

Container c = getContentPane();
  setContentPane(c);
   setContentPane(new JLabel(new ImageIcon("Chrysanthemum.jpg")));

最佳答案

一种可能是在JFrame中添加一个BorderLayout,它应该用JLabel填充JFrame,然后设置背景,添加将 JLabel 添加到框架中,然后向其添加组件,如下所示:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Foo extends JFrame {

    public Foo() {
        setLayout(new BorderLayout());


JLabel background = new JLabel(new ImageIcon("Untitled.png"));
    add(background);
    background.setLayout(new FlowLayout());
    background.add(new JButton("foo"));
    setSize(500, 500);
    setVisible(true);
}

public static void main(String[] args) {
    Foo foo = new Foo();
}
}

以上对我有用,JButton 位于 500 x 500 JFrame 的顶部中心,具有指定的背景。

关于java - 将图像设置为 JFrame 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356609/

相关文章:

java - 用作数组索引的字符是否隐式转换为字节/整数?

java - jmathplot - 旋转轴标签未对齐线图

Java:使用 BoxLayout 在 JPanel 中垂直移动 JButton

java - Jframe 根据条件进行处置

java - keyPressed 方法不工作 Java

java - 高效的输入流到java中的字符串方法

java - 如何解决Android中图像 slider 移动过快的问题?

java - spring @Aspect 无法与 swagger2 一起使用

java - 如何使JFrame模态像JOptionPane?

Java JFrame 图形更新