问题
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 JInternalFrame
s with the third one having a button which will output a list of JInternalFrame
s 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