这个问题已经有很多问题,但在任何地方答案都不尽人意。我可以得到一个JFrame显示背景图像只是通过扩展的JPanel和压倒一切的paintComponent细,像这样:JFrame中的背景图片
class BackgroundPanel extends JPanel {
private ImageIcon imageIcon;
public BackgroundPanel() {
this.imageIcon = Icons.getIcon("foo");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageIcon.getImage(), 0,0,imageIcon.getIconWidth(),imageIcon.getIconHeight(),this);
}
}
但现在,你如何在该背景上添加组件? 当我去
JFrame w = new JFrame() ;
Container cp = w.getContentPane();
cp.setLayout(null);
BackgroundPanel bg = new BackgroundPanel();
cp.add(bg);
JPanel b = new JPanel();
b.setSize(new Dimension(30, 40));
b.setBackground(Color.red);
cp.add(b);
w.pack()
w.setVisible(true)
它显示红色的小方(或任何其他组件),而不是背景,但是当我删除cp.setLayout(null);
,背景显示出来,但不是我的其他组件。我猜这与paintComponent没有被null LayoutManager调用有关,但我完全不了解LayoutManagers是如何工作的(这是一个专门针对大学的项目,并且该任务明确指出不使用LayoutManager) 。
当我让图像背景必须显示空(等,transparant(??))红色正方形显示,所以它可能是背景实际上高于我的其他组件。
有没有人有任何想法?
感谢
希望这个[线程](http://stackoverflow.com/a/11428289/1057230)也可能有一些帮助,在主题:-) – 2013-05-26 04:03:38