对于具有不同布局的面板(即 BoxLayout
布局管理器),我如何能够在面板上使用 Borderlayout.EAST
?面板本身不是必须能够使用 BorderLayout
管理器才能使用 BorderLayout.CONSTANT
吗?
JPanel jp1 = new JPanel();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.X_AXIS));
JPanel jp2 = new JPanel(new GridLayout());
jp1.add(jp2, BorderLayout.EAST); //This worked even though jp1 is a BoxLayout, how did it use BorderLayout?
最佳答案
这可能有点令人费解。当您将 add()
一个 Component
到 Container
时,addImpl()
处理请求。像 BorderLayout
这样的原始 LayoutManager
可以理解 BorderLayout.EAST
这样的常量,它具有 String
值 "East"
。较新的 LayoutManager2
,例如 BoxLayout
永远不会看到未使用的约束。特别是,
If the current layout manager implements
LayoutManager2
, thenLayoutManager2.addLayoutComponent(Component,Object)
is invoked on it. If the current layout manager does not implementLayoutManager2
, andconstraints
is aString
, thenLayoutManager.addLayoutComponent(String,Component)
is invoked on it.
附录:BoxLayout
同时实现 LayoutManager
和 LayoutManager2
。尽管 BoxLayout
必须提供 addLayoutComponent()
的两种变体,但该方法“未被此类使用”。实际上,BorderLayout.EAST
约束被忽略。
void addLayoutComponent(Component comp, Object constraints)
Not used by this class.
void addLayoutComponent(String name, Component comp)
Not used by this class.
关于java - 我怎样才能将 Borderlayout 常量用于不是不同布局管理器的面板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26252551/