我想提出一個小的應用程序,但我想在整個窗口設置圖像作爲背景。我試圖讓這個如下,但沒有發生。該圖像位於課程所在的文件夾中,因此我只放置了名稱......您能幫助我嗎?我能做什麼?將圖像設置爲背景的JFrame
Container c = getContentPane();
setContentPane(c);
setContentPane(new JLabel(new ImageIcon("Chrysanthemum.jpg")));
我想提出一個小的應用程序,但我想在整個窗口設置圖像作爲背景。我試圖讓這個如下,但沒有發生。該圖像位於課程所在的文件夾中,因此我只放置了名稱......您能幫助我嗎?我能做什麼?將圖像設置爲背景的JFrame
Container c = getContentPane();
setContentPane(c);
setContentPane(new JLabel(new ImageIcon("Chrysanthemum.jpg")));
一種可能性是一個BorderLayout
添加到JFrame,這應與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 by 500 JFrame
的頂部中心,並具有指定的背景。
它不起作用...我不知道爲什麼 – user3233650
我應該在哪裏有圖像?我有它與類相同的文件夾...我只指定的名稱...但它不工作 – user3233650
@ user3233650的方法是(大部分)是正確的,可能的原因,它不工作是的位置圖像不是你認爲它的地方... – MadProgrammer
我會做的是創建一個背景圖像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);
}
}
除非您想讓背景可以調整大小,否則這是浪費精力。此外,這種縮放圖像不考慮原始圖像的比例,通常不會產生好的結果 - 恕我直言 – MadProgrammer
當然ut不會工作,JLabel是一個標籤不是背景。 –
我怎麼能把圖像作爲背景? – user3233650
[This](http://stackoverflow.com/a/1065014/3226218)應該會幫助你。 – Didericis