我有一个小应用程序,应该演示不透明属性如何在 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 Internals: Paint Order :
幕后出了什么问题?
容器保存包含所有子组件的数组。对于绘制,Swing(更精确 JComponent#paintChildren())
以相反的顺序迭代数组 - 这意味着最后添加的第一个组件将被绘制。Z 顺序修改此数组中的子位置。如果布局管理器使用Container#getComponents()
(正如许多 Swing 核心布局管理器所做的那样)无法保证数组顺序代表组件添加到容器中的顺序。
通常在 Swing 中,您可以通过应用组件 Z-Order 来指定绘制顺序(请参阅 Container#setComponentZOrder)
。只要您使用空布局或使用约束的布局管理器,此方法就很有用。
使用 #setComponentZOrder
的缺点是它会影响组件的位置。
关于java - 添加到 JPanel 的组件按什么顺序绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25243369/