我正在制作一个小应用程序,但我想将图像设置为整个窗口的背景。我试着像下面那样做,但什么也没发生。该图像位于类(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/