这个问题已经被问了很多次,但是到处的答案都不够完整。我可以通过扩展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);
时,背景出现了,但我的其他组件没有出现。我猜这与null LayoutManager未调用paintComponent有关,但我对LayoutManager的工作方式一点也不熟悉(这是大学项目,任务明确指出不使用LayoutManager)。当我将图像设置为背景时,必须显示null(因此透明(??)),红色方块就会出现,所以背景实际上可能在我的其他组件之上。
有人有什么想法吗?
谢谢