java 是否可以将 JPanel 叠加在另一个之上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15961505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to overlay a JPanel on top of another?
提问by sdasdadas
I am attempting to overlay a smaller panel (sub
) over a larger panel (parent
). The dimensions of sub are smaller than that of parent.
我试图将较小的面板 ( sub
) 覆盖在较大的面板 ( parent
) 上。sub 的尺寸小于 parent 的尺寸。
JPanel sub = new JPanel();
JPanel parent = new CustomPanel();
I would like to override parent's paintComponent
method to draw sub in the top left hand corner with an offset of 5 pixels from the top and left sides. It would look something like this:
我想覆盖父的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?
Is it possible to tell sub to paint itself at a specific location? Terrible idea?
是否可以告诉 sub 在特定位置绘制自己?可怕的想法?
回答by Eugene Ryzhikov
Why don't you just setLayout(null)
on the parent panel and then, before adding the sub panel to parent , set it's position and dimensions using it's setBounds
method. This way there is no need to use paintComponent
for positioning the sub panel.
为什么不只是setLayout(null)
在父面板上,然后在将子面板添加到 parent 之前,使用它的setBounds
方法设置它的位置和尺寸。这样就不需要paintComponent
用于定位子面板。
Is case you parent panel should have specific layout with other components and sub should overlay all that, look into JLayer(Java 7) / JXLayer(Java 6).
如果您的父面板应该与其他组件具有特定的布局,而子面板应该覆盖所有这些,请查看JLayer(Java 7) / JXLayer(Java 6)。
Third solution can be using JLayeredPane.
第三个解决方案可以使用JLayeredPane。