2013-04-12 23 views
0

我试图在较大的面板(parent)上覆盖较小的面板(sub)。 sub的尺寸小于父代的尺寸。是否有可能覆盖另一个JPanel?

JPanel sub = new JPanel(); 
JPanel parent = new CustomPanel(); 

我想代替父母的paintComponent方法来绘制子在左上角与从顶部和左侧5个像素的偏移量。它看起来像这样:

class CustomPanel extends JPanel() { 

    JPanel sub = null; 

    public CustomPanel(JPanel sub) { 
     this.sub = sub; 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     this.paintComponent(g); 
     // TODO: Here is where I would call something like sub.paint(); 
     // However, I want sub to "start its paint" 5 pixels inside of 
     // parent's dimensions. How do I specify this? 

是否有可能告诉子画自己在一个特定的位置?可怕的想法?

回答

3

为什么不在父面板上只是setLayout(null),然后在将子面板添加到父面板之前,使用它的setBounds方法设置它的位置和尺寸。这样就不需要使用paintComponent来定位子面板。

如果你的父面板应该有其他组件的特定布局,并且子应该覆盖所有这些,请查看JLayer(Java 7)/ JXLayer(Java 6)。

第三种解决方案可以使用JLayeredPane

+0

问题在于'parent'还包含组件的非平凡布局。覆盖层('sub')应该画出它们 - 但我不认为我可以摆脱手动定位它们。 – sdasdadas

+0

查看更新的答案 –

+0

添加了第三个解决方案 –

相关问题