我试图将较小的面板(sub
)覆盖在较大的面板(parent
)上。子元素的尺寸小于父元素
JPanel sub = new JPanel();
JPanel parent = new CustomPanel();
我想重写父的paintComponent
方法,在左上角绘制sub,从顶部和左侧偏移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?
有可能告诉sub在一个特定的位置油漆自己吗?可怕的主意吗?
为什么不在父面板上添加setLayout(null)
,然后在将子面板添加到父面板之前,使用它的setBounds
方法设置它的位置和尺寸。这样就不需要使用paintComponent
来定位子面板了。
如果你的父面板应该与其他组件有特定的布局,子面板应该覆盖所有这些,查看JLayer(Java 7)/JXLayer(Java 6)。
第三个解决方案可以使用JLayeredPane