簡體   English   中英

按什么順序將組件添加到JPanel?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM