How to get the z order of JInternalFrames in a JDesktopPane

狂风中的少年 提交于 2019-12-12 09:42:28

问题


How would one go about getting the z order (layer depth of ) all the JInternalFrames inside a JDesktopPane. There does not seem to be a straight forward way for this. Any ideas?


回答1:


Although I haven't tried this, the Container class (which is an ancestor of the JDesktopPane class) contains a getComponentZOrder method. By passing a Component which is in the Container, it will return the z-order of as an int. The Component with the lowest z-order value returned by the method is drawn last, in other words, is drawn on top.

Coupling with the JDesktopPane.getAllFrames method, which returns an array of JInternalFrames, I would think that one could obtain the z-order of the internal frames.

Edit

I've actually tried it out and it seems to work:

final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JDesktopPane desktopPane = new JDesktopPane();
desktopPane.add(new JInternalFrame("1") {
    {
        setVisible(true);
        setSize(100, 100);
    }
});
desktopPane.add(new JInternalFrame("2") {
    {
        setVisible(true);
        setSize(100, 100);
    }
});
desktopPane.add(new JInternalFrame("3") {
    JButton b = new JButton("Get z-order");
    {
        setVisible(true);
        setSize(100, 100);
        getContentPane().add(b);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                JInternalFrame[] iframes = desktopPane.getAllFrames();
                for (JInternalFrame iframe : iframes)
                {
                    System.out.println(iframe + "\t" +
                            desktopPane.getComponentZOrder(iframe));
                }
            }
        });
    }
});

f.setContentPane(desktopPane);
f.setLocation(100, 100);
f.setSize(400, 400);
f.validate();
f.setVisible(true);

In the above example, a JDesktopPane is populated with three JInternalFrames with the third one having a button which will output a list of JInternalFrames and its z-order to System.out.

An example output is the following:

JDesktopPaneTest$3[... tons of info on the frame ...]    0
JDesktopPaneTest$2[... tons of info on the frame ...]    1
JDesktopPaneTest$1[... tons of info on the frame ...]    2

The example uses a lot of anonymous inner classes just to keep the code short, but an actual program probably should not do that.



来源:https://stackoverflow.com/questions/624885/how-to-get-the-z-order-of-jinternalframes-in-a-jdesktoppane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!