[英]in which order are components added to a JPanel drawn?
我有一个小应用程序,该应用程序应演示opaque属性在Swing中的工作方式。 但是,让我失望的是paintComponent()
的调用顺序。 我认为组件是按添加顺序绘制的(首先添加的是什么,先绘制),但是在此示例中, paintComponent()
方法似乎是按相反顺序绘制的(最后添加的是首先绘制的),有人可以吗?解释这种行为,谢谢
public class TwoPanels {
public static void main(String[] args) {
JPanel p = new JPanel();
// setting layout to null so we can make panels overlap
p.setLayout(new BorderLayout());
CirclePanel topPanel = new CirclePanel("topPanel1");
// drawing should be in blue
topPanel.setForeground(Color.blue);
// background should be black, except it's not opaque, so
// background will not be drawn
topPanel.setBackground(Color.black);
// set opaque to false - background not drawn
topPanel.setOpaque(false);
topPanel.setBounds(50, 50, 100, 100);
// add topPanel - components paint in order added,
// so add topPanel first
p.add(topPanel);
CirclePanel bottomPanel = new CirclePanel("buttomPanel1");
// drawing in green
bottomPanel.setForeground(Color.green);
// background in cyan
bottomPanel.setBackground(Color.cyan);
// and it will show this time, because opaque is true
bottomPanel.setOpaque(true);
bottomPanel.setBounds(30, 30, 100, 100);
// add bottomPanel last...
p.add(bottomPanel);
// frame handling code...
JFrame f = new JFrame("Two Panels");
f.setContentPane(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// Panel with a circle drawn on it.
private static class CirclePanel extends JPanel {
String objName;
public CirclePanel(String objName) {
this.objName = objName;
}
// This is Swing, so override paint*Component* - not paint
protected void paintComponent(Graphics g) {
System.out.println(objName);
// call super.paintComponent to get default Swing
// painting behavior (opaque honored, etc.)
super.paintComponent(g);
int x = 10;
int y = 10;
int width = getWidth() - 20;
int height = getHeight() - 20;
g.fillArc(x, y, width, height, 0, 360);
}
}
}
从Swing内部:油漆顺序 :
到底是怎么回事?
容器包含具有所有子组件的数组。 对于绘画,Swing(更精确的JComponent#paintChildren())
以相反的顺序遍历数组-这意味着最后添加的第一个组件将被绘画。 Z顺序修改此数组中的子位置。 如果布局管理器使用Container#getComponents()
(就像许多Swing核心布局管理器一样),则不能保证数组顺序代表组件添加到容器中的顺序。
通常,在Swing中,您可以通过应用组件Z-Order来指定绘制顺序(请参见Container#setComponentZOrder)
。 只要您使用空布局或使用约束的布局管理器,此方法就很有用。
使用#setComponentZOrder
的缺点是它会影响组件位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.