我正在使用 JPanel 来模拟正方形。这个想法是在 JPanel 前面放置一种过滤器。
第一个 JPanel 包含一个 ImageIcon 和一个背景颜色。包含透明背景颜色的第二个 JPanel 放在第一个 JPanel 内。
我做到了,但我遇到了一个问题:顶部出现了第二个 JPanel 没有覆盖第一个 JPanel 的边距。
编辑:代码类 JPanelImage 扩展 JPanel
private ImageIcon imageIcon = null;
public void paintComponent(Graphics g)
{
if(imageIcon != null)
{
Image image = imageIcon.getImage();
int height = 30;
int width = 18;
int marginLeft = (this.getWidth()-width) / 2;
int marginTop = (this.getHeight()-height) / 2;
super.paintComponent(g);
g.drawImage(image, marginLeft, marginTop, width, height, this);
}
else
super.paintComponent(g);
}
public void addColoredLayout(Color color) {
JPanelImage upperLayout = new JPanelImage();
upperLayout.setOpaque(true);
upperLayout.setBackground(color);
upperLayout.setPreferredSize(this.getPreferredSize());
this.add(upperLayout);
}
我还有一个创建 JPanel 并应用 addColoredLayout 方法的 Window 类(扩展 JFrame)。