这个问题已被问到很多,但到处都是答案不足.我可以通过扩展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) .
当我制作图像时,背景必须显示为null(因此,透明(??))红色方块显示,因此可能是背景实际上高于我的其他组件.
有没有人有任何想法?
谢谢