[英]Set an image as background to JFrame
我正在制作一个小应用程序,但是我想在整个窗口中将图像设置为背景。 我试图使它像下面一样,但是什么也没有发生。 该图像位于该类所在的文件夹中,因此我只输入名称...您能帮我吗? 我能做什么?
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
, JButton
位于指定背景的500 x 500 JFrame
的顶部中心。
我要做的是创建一个带有背景图像的JPanel
,并将其添加到JFrame
。 我的一个项目中已经有一个BackgroundPanel
类,这就是我要的设置。
public class MyFrame extends JFrame {
private BackgroundPanel bgPanel;
public MyFrame() {
bgPanel = new BackgroundPanel("Chrysanthemum.jpg");
setTitle("MyFrame");
setResizable(false);
setContentPane(bgPanel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
// -- BackgroundPanel class
public class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image bg;
public BackgroundPanel(String path) {
this(Images.load(path).getImage());
}
public BackgroundPanel(Image img) {
this.bg = img;
setPreferredSize(new Dimension(bg.getWidth(null), bg.getHeight(null)));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.