4

我正在为一个学校 Java 项目开发 Connect Four 游戏。我已经了解了 JLayeredPane 的“如何”,它按预期工作,但我不太了解某个概念背后的“为什么”。

以下是我的理解:

JLayeredPane 是一个容器,类似于 JPanel,它允许您为每个组件指定深度和位置。Depth 是一个整数,0 是底层,n-1 是顶层,n 是组件的数量。Position 是一个 int(是的,一个使用 Integer 包装类,一个只是一个基元!)指定组件在层内的位置,0 是最顶层,-1 是最底层,正整数之间,数字越小位置越高。因此,可以将单层中的四个组件从最高到最低排序到位置 0、1、2、-1。

我的问题是,有什么需要同时拥有这两个概念?

例如,我创建了三个带有图像的 JLabel:前板、后板和一块。棋子有时在frontBoard 前面,有时在frontBoard 和backBoard 之间。让我们检查第二个例子。

我可以通过以下任何一种方式获得相同的效果:

1)我可以将背板设置为第0层,位置0;该片到第 1 层,位置 0;和前板到第 2 层,位置 0

 or 

2)我可以将背板设置为第0层,位置-1;该片到第 0 层,位置 1;和 frontBoard 到第 0 层,位置 0

我已经测试了这两种方法,我找不到这两种方法之间的功能差异。

谁能帮我解开这个谜团?

4

1 回答 1

2

首先,在这种情况下最好的办法是看一下教程,它们通常信息量很大:http: //download.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

此外,该类本身的 javadoc 包含对 JLayeredPane 工作方式的很好的解释。

由于您已经实现了项目,因此您知道可以通过两种不同的方式实现组件的堆叠:将每个组件放在自己的层上,或者通过为同一层上的不同组件分配不同的位置值。效果是一样的,但是你会使用两个不同的属性来实现它:

  • "depth" is a property of the layer: they are enumerated so that the layer with depth 0 is furthest the lowest of all. Layers with higher depths cover layers with lower depths.
  • Since layers can contain more than one component and since components can always overlap, there must be a way to define the z-order of the components within the layer: that is achieved by enumerating the components with a "position" value. If there are n components in the layer and you start counting at 0, then a position must be a value in the range between 0 and n-1.

Now you could argue that since you have the "position" value, you don't need multiple layers at all, since you can position all components along the z-axis simply through their "position" value. That is true and nobody keeps you from doing so.

The rationale for multiple layers can be seen when you realize that there a predefined constants to be used for the "depth" value of the layers:

  • DEFAULT_LAYER
  • PALETTE_LAYER
  • MODAL_LAYER
  • POPUP_LAYER
  • DRAG_LAYER

These are are just logical groupings for complex multi-window applications that help you make sure that some stacking constraints are met: imagine you want to create a modal dialog window that appears on top of your main application frame. If you use a single layer, you must keep track of the positions of all visible components yourself and set the position of the dialog to n. Now add in drag and drop animations, popup menus, etc. and this task becomes quite complex.

By using predefined layers this complexity is reduced. If you want to display a modal dialog window, you don't care about the components of the main application window, you just place it on the MODAL_LAYER and you're done: you can be certain that it's displayed on top of all other components.

Luckily, Swing does all this stuff for you already (by using JLayeredPane or subclasses thereof internally), so you can just call setVisible(boolean) or setModal(boolean) on a JDialog and it will turn out the way you expect it to.

于 2010-11-30T18:55:52.363 回答